Skip to content

Majority Element

Find the value that fills more than half of an array, counting with a hash map and stopping early.

EasyHashing
Solve on LeetCode

The problem

You get an integer array nums of length n. One value appears more than n / 2 times, and you can assume such a value always exists. Return that value.

Input nums = [5, 1, 5, 2, 5]

Output 5

5 appears 3 times out of 5, which is more than half.

Input nums = [8, 8, -3, -3, -3, 8, 8]

Output 8

8 appears 4 times out of 7; -3 appears only 3 times.

Key constraint: The majority value fills more than half the array, so there is exactly one answer and it outnumbers all the other values put together.

How to spot the pattern

  • You need to know how many times each value appears.
  • The answer is defined by a count crossing a line: more than n / 2.

The idea

Count how often each value appears, using a hash map from value to count. The moment any count goes past n / 2, that value must be the majority, because two different values can't both fill more than half the array. So a single pass that stops at that moment is enough.

Brute force: For each value, count its copies with a second loop over the array, which takes O(n^2) time.

Step by step

  1. 1Create an empty map from value to count.
  2. 2Walk through the array and add 1 to the count of each number.
  3. 3Right after updating a count, check whether it is greater than n / 2.
  4. 4If it is, return that number; the problem promises this happens before the loop ends.

See the pattern move

The hashing pattern on a small example. Step through it, or press play.

Code

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        counts = {}  # value -> how many times we have seen it
        for num in nums:
            counts[num] = counts.get(num, 0) + 1
            if counts[num] > len(nums) // 2:
                return num
        return -1  # not reached: a majority value always exists

Complexity

Time

O(n)

Space

O(n)

One pass with O(1) map work per number; the map can hold up to about n / 2 different values.

Watch out for

  • Checking count >= n / 2 instead of count > n / 2: in [2, 2, 3, 3, 3] the 2 reaches 2 copies first and is returned by mistake.
  • Reading a missing key as a number: use getOrDefault in Java and (counts.get(num) || 0) in JavaScript, or the first count of each value breaks.

Follow-up questions

Can you do it in O(1) extra space?

Yes, with Boyer-Moore voting. Keep a candidate and a count: when the count is 0, take the current number as the candidate, then add 1 if the number equals the candidate and subtract 1 otherwise. Each vote against the majority cancels at most one of its copies, and it has more copies than everything else combined, so it is the candidate left at the end.

What if you need every value that appears more than n / 3 times?

There can be at most two such values. Run the vote with two candidates and two counters, then make a second pass to check that each candidate really appears more than n / 3 times. That is Majority Element II.

In Hinglish

Har value ki ginti map mein rakho; jaise hi kisi ki ginti n/2 se upar jaaye, wahi majority hai, wahin return kar do.

Related problems