Skip to content
Problem 229 · LeetCode 229(opens in a new tab)

Majority Element II

MediumArrays

You are given an array of integers nums of length n. Find every value that shows up more than n / 3 times, rounding n / 3 down.

Return those values in any order. There can be none, one or two of them.

Example 1

Input:  nums = [4, 1, 4, 4, 2]
Output: [4]
Why:    4 appears 3 times, more than 5 // 3 = 1
2 more examples and the constraints

Example 2

Input:  nums = [5, 7, 5, 2, 7, 5, 7]
Output: [5, 7]
Why:    each appears 3 times, more than 7 // 3 = 2

Example 3

Input:  nums = [3, 9, 1]
Output: []
Why:    every value appears once, and 1 is not more than 3 // 3

Constraints

  • 1 ≤ length of nums ≤ 50,000
  • −1,000,000,000 ≤ nums[i] ≤ 1,000,000,000
  • Follow-up: use O(n) time and O(1) extra space

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count with a hash mapO(n)
  2. Boyer–Moore voting with two candidatesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 numbersVerdict
Count with a hash mapO(n)
Passes; uses O(n) memory
Boyer–Moore voting with two candidatesO(n)
Best; O(1) memory

n = length of nums. Both are linear; voting avoids hashing and keeps no map.

Edge cases to test

  • No answer. [3, 9, 1] returns an empty list.
  • Exactly a third is not enough. In [1, 1, 2, 2, 3, 3] each value appears 2 times, which is not more than 2.
  • Two short arrays. [6, 8] returns both: each appears once, more than 2 // 3 = 0.
  • Values equal to the starting candidates. In [0, 0, 1, 1, 2] the answer is [0, 1]; the counting pass must not trust slots that were never really filled.

Common mistakes

  • Returning the two vote survivors without counting them again.
  • Using >= n / 3 instead of >, so a value that fills exactly a third gets in.
  • Letting both slots hold the same value, which then gets counted and returned twice.

How to talk through it

  1. 1Clarify. Is it strictly more than n / 3, rounded down? Can the answer be empty? Any order?
  2. 2Give the map. Count everything in a hash map: O(n) time, O(n) space.
  3. 3Bound the answer. Three values each above n / 3 would need more than n items, so at most two qualify.
  4. 4Code the vote. Two candidates, two counters; cancel one from each on a third value; then a counting pass.
  5. 5Test out loud. Run an empty answer, a value at exactly a third and a two-item array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?