Majority Element II (LeetCode 229): Solution and Explanation

Medium
Array
Hash Table
Sorting
Counting

Given an integer array of length n, return every value that appears more than ⌊n / 3⌋ times, in any order. The follow up asks for linear time and constant extra space, which rules out a hash map of counts.

Intuition

Start with a counting fact. If three different values each appeared more than n/3 times, together they would need more than n elements. So the answer has at most two values, and two slots are enough to track the suspects.

Boyer-Moore voting for the classic majority problem pairs off one majority element against one different element until only the majority survives. Here the same trick works with triples. Whenever you see three pairwise different values, throw all three away. A value that appears more than n/3 times cannot be wiped out, because each removal costs it at most one copy while removing two other elements as well, and there are not enough other elements to pay for all of its copies.

In code the triple removal looks like this: the current number matches neither candidate and both slots hold votes, so you subtract one vote from each candidate and drop the number. Matching numbers add a vote, and a number arriving at an empty slot takes it over.

The two survivors are only suspects. An array with no qualifying value still leaves something in the slots, so a second pass counts each candidate and keeps only those above the n/3 threshold.

Approach: Boyer-Moore voting with two candidates

  1. Set cand1, cand2 = 0, 1 (any two different values) and both counts to 0.
  2. For each x: if x == cand1, increment count1; else if x == cand2, increment count2.
  3. Otherwise, if count1 == 0, set cand1 = x, count1 = 1; else if count2 == 0, set cand2 = x, count2 = 1.
  4. Otherwise, decrement both counts. This removes x, one copy of cand1 and one copy of cand2 together.
  5. After the scan, count how often each candidate really appears and return those with a count above len(nums) // 3.

Step-by-step example

nums = [3,2,3]
  1. Start with cand1 = 0, cand2 = 1, both counts 0. The threshold is 3 // 3 = 1.
  2. x = 3: it matches neither candidate and count1 is 0, so 3 takes slot 1 with count1 = 1.
  3. x = 2: it matches neither candidate, count1 is 1, count2 is 0, so 2 takes slot 2 with count2 = 1.
  4. x = 3: it matches cand1, so count1 = 2.
  5. Verify: 3 appears 2 times, more than 1, so keep it. 2 appears once, not more than 1, so drop it. The answer is [3].

Code: Python, Java, C++

1class Solution:
2    def majorityElement(self, nums: List[int]) -> List[int]:
3        cand1, cand2, count1, count2 = 0, 1, 0, 0
4        for x in nums:
5            if x == cand1:
6                count1 += 1
7            elif x == cand2:
8                count2 += 1
9            elif count1 == 0:
10                cand1, count1 = x, 1
11            elif count2 == 0:
12                cand2, count2 = x, 1
13            else:
14                count1 -= 1
15                count2 -= 1
16        res = []
17        for c in (cand1, cand2):
18            if nums.count(c) > len(nums) // 3:
19                res.append(c)
20        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Boyer-Moore voting with two candidates O(n)
Hash map of counts O(n)
Sort and scan runs O(n log n)
Time

O(n)

One pass to vote and one pass to count the two candidates, each doing constant work per element.

Space

O(1)

Only two candidates, two counts and the at most two element result are stored.

Other approaches

Hash map of counts (time O(n), space O(n))

Count every value in a dictionary and return the keys whose count exceeds n // 3. It is the simplest correct solution and fine in an interview warm up, but it uses memory proportional to the number of distinct values.

Sort and scan runs (time O(n log n), space O(1) to O(n))

Sort the array so equal values sit together, then measure each run length. It needs no extra map, but sorting costs O(n log n) and modifies the input unless you copy it.

Common mistakes

  • Skipping the verification pass. The voting phase always leaves two candidates, even for input like [1,2,3] where nothing qualifies.
  • Checking count1 == 0 before checking whether x equals cand2. That can put the same value in both slots and later report it twice.
  • Using >= instead of > against n // 3. A value must appear strictly more than a third of the time.
  • Treating count1 and count2 as frequencies. They are net votes after cancelling, so they can be far below the real count and cannot replace the verification pass.

Frequently asked questions

Why can there be at most two answers?

Each answer needs more than n/3 occurrences. Three such values would need more than n elements in total, which is impossible.

Why does cancelling three different values never lose a real winner?

Each cancel removes at most one copy of the winner and two other elements. A winner has more than n/3 copies, so there are fewer than 2n/3 other elements, which is not enough to cancel every copy of it.

Why are the initial candidates 0 and 1?

They only need to be different from each other. Their counts start at 0, so the first new values take the slots, and a starting value that never appears fails the verification pass.

What is the time and space complexity of Majority Element II?

O(n) time for the voting pass plus the verification pass, and O(1) extra space.