Skip to problem
←

Majority Element

Easy 0 attempts

You're given an array nums of length n. Return its majority element — the value that shows up more than ⌊n / 2⌋ times. You can assume such an element always exists in the input.

Because it has to appear in more than half the positions, there can only ever be one candidate that qualifies.

Function contract

Implement majorityElement(nums). Receive a nonempty integer array with a guaranteed majority element.

Output: Return the majority value, not its count or index.

Example 1

Input
nums = [3,2,3]
Output
3

Example 2

Input
nums = [1]
Output
1
Constraints
  • 1 <= nums.length <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9
  • An element occurring more than floor(nums.length / 2) times is guaranteed to exist

Boyer-Moore Voting Algorithm. Maintain a candidate and a counter. Walk through the array: if the counter is zero, pick the current element as the new candidate. Increment the counter when the element matches the candidate, decrement otherwise. The majority element always survives because it appears more than half the time.

Think of each decrement as cancelling a pair of different values. Removing such a pair cannot eliminate the strict majority among the remaining elements. The surviving candidate is therefore the answer. The existence guarantee matters: without it, a second pass would be needed to verify the candidate's frequency.

javascript
function majorityElement(nums) {
  let candidate = nums[0];
  let count = 0;

  for (const num of nums) {
    if (count === 0) candidate = num;
    count += (num === candidate) ? 1 : -1;
  }

  return candidate;
}

Time: O(n) — single pass. Space: O(1) — only two variables.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript