Majority Element

Difficulty: Easy

You're given a list where one value appears more than half the time (strictly more than n/2 times, where n is the list's length). Return that value.

Such a value always exists.

Examples

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

3 appears twice out of three elements - more than half.

Input: nums = [2, 2, 1, 1, 1, 2, 2]
Output: 2

2 appears 4 times out of 7, which is more than half.

Input: nums = [1]
Output: 1

Constraints

  • 1 <= nums.length <= 5 * 10^4

  • A majority element (appearing more than n/2 times) always exists.

Approach

The simple approach counts each number with a hash map and returns the one whose count passes n/2.

Boyer-Moore voting needs no extra memory. Keep a "candidate" and a counter starting at zero. Walk the list:

  • If the counter is zero, make the current number the candidate.
  • Add 1 if the number matches the candidate, or subtract 1 if not.

The majority element outnumbers everything else combined, so it can't be fully cancelled out. The candidate left at the end is the answer.

Solutions

Brute Force - Count With a Hash Map

Count each number with a hash map. As soon as a count passes n/2, return that number.

function majorityElement(nums) {
  const counts = new Map();
  const majorityThreshold = Math.floor(nums.length / 2);

  for (const num of nums) {
    counts.set(num, (counts.get(num) || 0) + 1);
    if (counts.get(num) > majorityThreshold) {
      return num;
    }
  }
}

Time: O(n) · Space: O(n)

Optimal - Boyer-Moore Voting

Keep a candidate and a counter, both starting empty. For each number, if the counter is zero, make it the candidate. Then increase the counter if the number matches the candidate, or decrease it otherwise. The majority element can't be fully cancelled out, so it's the candidate left at the end.

function majorityElement(nums) {
  let candidate = null;
  let count = 0;

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

  return candidate;
}

Time: O(n) · Space: O(1)