☰ All problems

11. Majority Element

Given an array nums of length n, return its majority element: the value that occurs more than n / 2 times (strictly more than half of the array).

Every test is guaranteed to have a majority element.

Example 1
Input: nums = [5,1,5]
Output: 5

Explanation: 5 appears twice out of three elements.

Example 2
Input: nums = [4,7,7,4,7,7,4]
Output: 7

Explanation: 7 appears 4 times, which is more than 7 / 2 = 3.5.

Example 3
Input: nums = [9]
Output: 9

Constraints

  • 1 <= nums.length <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9
  • A majority element always exists.

Follow-up: Can you solve it in linear time using only O(1) extra space?

💡 Hint 1

Counting occurrences in a hash map is O(n) time but O(n) space. Sorting also works: which index must the majority element occupy after sorting?

💡 Hint 2

For O(1) space, pair up each occurrence of the majority value with a different value and cancel them out. Since it fills more than half the array, something of it survives.

💡 Hint 3

Keep a candidate and a count: when count is 0, adopt the current value; add 1 when you see the candidate and subtract 1 otherwise.

/**
 * @param {number[]} nums
 * @return {number}
 */
function majorityElement(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc