Majority Element II

Pattern: Majority element (Boyer-Moore)

medium

At most two values can appear more than n/3 times, so run the vote with two candidates. A value that matches neither cancels a vote from both, and a second pass checks the survivors.

The problem

Given an array of n whole numbers, return every value that appears more than n/3 times. There may be none, one or two. For example, [3, 2, 3] gives [3], [1, 2] gives [1, 2], and [4, 5, 6, 7] gives [].

The function name majorityElement matches LeetCode, which accepts the values in any order. This guide returns them in increasing order.

Think first

  • How many different values can each appear more than n/3 times?
  • How would you change the one-candidate vote to keep that many candidates?
  • Is every survivor of the vote really above n/3?

Hints

    Brute force, and why it fails

    Count every value with a hash map: O(n) time but O(n) memory. Sorting and scanning runs is O(n log n). The two-candidate vote is O(n) time and O(1) memory.

    The key insight

    Each cancellation removes three different values at once. A value with more than n/3 copies cannot be cancelled completely, so it must be one of the two survivors.

    Dry run

    10 
    11 
    12 
    33 
    34 
    25 
    26 
    27 
    A1
    countA3
    Bnone
    countB0

    nums = [1, 1, 1, 3, 3, 2, 2, 2]. Two slots start empty. The three 1s fill slot A with count 3.

    Step 1 of 5

    The plan

    cand1 = none, cand2 = none, count1 = 0, count2 = 0
    for v in nums:
        if v == cand1: count1 = count1 + 1
        else if v == cand2: count2 = count2 + 1
        else if count1 == 0: cand1 = v; count1 = 1
        else if count2 == 0: cand2 = v; count2 = 1
        else: count1 = count1 - 1; count2 = count2 - 1
    result = candidates whose real count is more than n / 3
    return result in increasing order
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two passes over the array with four numbers, and a result of at most two values.

    Edge cases

    • No value passes, as in [4, 5, 6, 7]: [].
    • One value only, as in [0, 0, 0]: [0], and the second candidate must not repeat it.
    • n/3 rounds down: with n = 8, a value needs at least 3 copies.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> majorityElement(int[] nums) {
            int cand1 = 0, cand2 = 1, count1 = 0, count2 = 0;   // two different starting candidates
            for (int v : nums) {
                if (v == cand1) count1++;
                else if (v == cand2) count2++;
                else if (count1 == 0) { cand1 = v; count1 = 1; }
                else if (count2 == 0) { cand2 = v; count2 = 1; }
                else { count1--; count2--; }       // v cancels one vote from each candidate
            }
            List<Integer> result = new ArrayList<>();
            count1 = 0;
            count2 = 0;
            for (int v : nums) {                    // second pass: the candidates are only possibilities
                if (v == cand1) count1++;
                else if (v == cand2) count2++;
            }
            if (count1 > nums.length / 3) result.add(cand1);
            if (count2 > nums.length / 3) result.add(cand2);
            Collections.sort(result);
            return result;
        }
    }

    C++

    class Solution {
    public:
        vector<int> majorityElement(vector<int>& nums) {
            int cand1 = 0, cand2 = 1, count1 = 0, count2 = 0;   // two different starting candidates
            for (int v : nums) {
                if (v == cand1) count1++;
                else if (v == cand2) count2++;
                else if (count1 == 0) { cand1 = v; count1 = 1; }
                else if (count2 == 0) { cand2 = v; count2 = 1; }
                else { count1--; count2--; }       // v cancels one vote from each candidate
            }
            vector<int> result;
            count1 = 0;
            count2 = 0;
            for (int v : nums) {                    // second pass: the candidates are only possibilities
                if (v == cand1) count1++;
                else if (v == cand2) count2++;
            }
            int n = static_cast<int>(nums.size());
            if (count1 > n / 3) result.push_back(cand1);
            if (count2 > n / 3) result.push_back(cand2);
            sort(result.begin(), result.end());
            return result;
        }
    };

    Python

    class Solution:
        def majorityElement(self, nums: list[int]) -> list[int]:
            cand1, cand2, count1, count2 = 0, 1, 0, 0       # two different starting candidates
            for v in nums:
                if v == cand1:
                    count1 += 1
                elif v == cand2:
                    count2 += 1
                elif count1 == 0:
                    cand1, count1 = v, 1
                elif count2 == 0:
                    cand2, count2 = v, 1
                else:
                    count1 -= 1                     # v cancels one vote from each candidate
                    count2 -= 1
            # second pass: the candidates are only possibilities
            return sorted(c for c in (cand1, cand2) if nums.count(c) > len(nums) // 3)

    Common mistakes

    • Skipping the second pass. In [1, 2, 3] the candidates end as 1 and 2, but each appears once, which is not more than 3/3 = 1, so the answer is [].
    • Checking the empty slots before checking for a match, which can put the same value in both slots.
    • Starting both candidates at the same value, so one value fills both slots. The code starts them at two different values.

    Similar problems