Majority Element II

Medium

Topics
ArrayHash TableSorting

Given an integer array nums of size n, return all elements that appear more than ⌊n/3⌋ times, sorted in ascending order.

Example 1

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

Example 2

10
Input:  nums = [1]
Output: [1]

Example 3

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

Constraints

  • 1 <= nums.length <= 5*10^4
  • -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

We want every value appearing more than n/3 times. The first thing to establish is how many there can be: three such values would need more than n occurrences between them, so there are at most two. That bound is what makes the problem tractable and is worth stating before any code.

Counting every value and filtering is O(n) time and O(n) space, which is what the shown solution does. The final sort is over at most two values, so it costs nothing.

The O(1)-space answer is Boyer-Moore extended to two candidates, and it is the expected follow-up. Hold two candidate values with two counters; for each element, match it to a candidate, or claim an empty slot, or decrement both. The survivors are the only possible answers — and because the algorithm can produce false positives, a second pass is mandatory to verify each candidate actually exceeds n/3.

Approach

  1. Count occurrences of each value.
  2. Return those with count * 3 > n.

Dry Run

nums = [1,1,1,3,3,2,2,2]   n = 8, threshold n/3 = 2.67

counts  1 -> 3    3 -> 2    2 -> 3

1: 3*3 = 9 > 8   qualifies
3: 2*3 = 6 < 8   does not
2: 3*3 = 9 > 8   qualifies

answer [1,2]

Using count * 3 > n rather than count > n / 3 keeps the comparison in integers and avoids a rounding question at the boundary.

Complexity

  • Time — O(n): one counting pass. The trailing sort is over at most two elements, so it does not affect the bound.
  • Space — O(n) for the counter in the worst case of all-distinct values. The two-candidate Boyer-Moore variant is O(1), which is the only reason to prefer it.

Common Pitfalls

  • Not knowing the answer has at most two elements. It bounds the problem and is the first thing an interviewer probes.
  • Using >= instead of >. The requirement is strictly more than n/3, so exactly n/3 does not qualify.
  • Comparing with floating-point division, which can mis-handle the boundary. Multiply instead.
  • In the Boyer-Moore variant, skipping the verification pass. The candidates are only possible answers, and without the second pass an input with no qualifying value returns garbage.
  • In the Boyer-Moore variant, checking the two candidate slots in the wrong order, so a value matching candidate two is wrongly assigned to an empty candidate one.

Full Solution — all languages

class Solution:
    def majorityElement(self, nums):
        from collections import Counter
        n = len(nums)
        cnt = Counter(nums)
        return sorted(v for v in cnt if cnt[v] * 3 > n)
SensAI
Beta
Tap the mic to stop voice mode