You get a list of whole numbers, nums, of length n. One value fills more than half of the list: it appears more than n / 2 times (rounded down). There is always such a value.
Return that value.
Example 1
Input: nums = [3, 8, 8, 3, 8, 8, 3] Output: 8 Why: 8 appears 4 times out of 7
2 more examples and the constraints
Example 2
Input: nums = [5] Output: 5 Why: one number is the whole list
Example 3
Input: nums = [7, 1, 7] Output: 7 Why: 7 appears twice out of 3
Constraints
- 1 ≤ n ≤ 50,000
- Every number is between −1,000,000,000 and 1,000,000,000
- Some value appears more than n / 2 times
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count with a hash mapO(n)
- Sort, take the middleO(n log n)
- Boyer–Moore votingO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 numbers | Verdict |
|---|---|---|---|
| Count with a hash map | O(n) | Passes; O(n) memory | |
| Sort, take the middle | O(n log n) | Passes; two lines | |
| Boyer–Moore voting | O(n) | Best; one pass, O(1) memory |
n = how many numbers are in the list.
Edge cases to test
- One number. [5] gives 5: the first read makes it the candidate.
- Answer arrives late. In [3, 1, 2, 7, 7, 7, 7] the candidate changes before 7 takes over.
- Answer spread thin. Copies of the answer can alternate with other values, so it never forms one long run in the input.
- Negative values. Do not use 0 or −1 as a "no candidate" marker that a real value could match by accident.
Common mistakes
- Checking
count >= n / 2instead ofcount > n / 2, which matters only when no answer is promised. - Changing the candidate when count drops to 0 instead of on the next number read.
- Returning the most frequent value seen so far mid-loop in the voting approach; the candidate is only safe after the full pass.
How to talk through it
- 1Clarify. Is a value above half always there? May I change the input? Is O(1) memory required?
- 2Give the counting map. One pass with a map is O(n) time but O(n) space.
- 3Mention sorting. The long run must cover the middle index, so sorted
nums[n // 2]is the answer. - 4Code the vote. Explain why cancelling pairs leaves the answer: it has more copies than all other values combined.
- 5Test out loud. Run a single number and a list where the candidate changes before the answer takes over.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?