Given an array of size n and a number k, fin all elements that appear more than " n/k " times

Pattern: Majority element (Boyer-Moore)

medium

The vote with k - 1 candidates. A value that fits no slot cancels one vote from every candidate. Survivors are checked with a second pass against n/k.

The problem

You are given an array of n whole numbers and a number k of at least 2. Return every value that appears more than n/k times, in increasing order. For example, [3, 1, 2, 2, 1, 2, 3, 3] with k = 4 gives [2, 3] (each appears 3 times, more than 2), and [9, 8, 7, 9, 2, 9, 7] with k = 3 gives [9].

The link above is a GeeksforGeeks article on this problem. The function name findElements and the increasing order of the result are this guide's own.

Think first

  • How many values can appear more than n/k times?
  • Majority Element II kept two candidates for n/3. How many do you need for n/k?
  • When a value fits no slot, what does cancelling remove, and why is that safe?

Hints

    Brute force, and why it fails

    A hash map of all counts is O(n) time and O(n) memory, and is a fine answer when memory is not a concern. Sorting and scanning runs is O(n log n). The vote uses O(k) memory and O(n·k) time.

    The key insight

    This is the general form of Boyer-Moore voting. With k - 1 slots, every cancellation removes k different values, which a frequent value cannot afford to lose entirely.

    Dry run

    90 
    81 
    72 
    93 
    24 
    95 
    76 
    slots9 ×1, 8 ×1

    arr = [9, 8, 7, 9, 2, 9, 7] and k = 3, so keep up to 2 candidates. 9 and 8 take the two slots with 1 vote each.

    Step 1 of 5

    The plan

    cand = empty map
    for v in arr:
        if v in cand: cand[v] = cand[v] + 1
        else if size of cand < k - 1: cand[v] = 1
        else:
            for every c in cand:
                cand[c] = cand[c] - 1
                if cand[c] == 0: remove c
    result = the keys of cand whose real count in arr is more than n / k
    return result in increasing order
    

    Complexity

    Time
    O(n·k)
    Space
    O(k)

    Each value may cancel up to k - 1 votes, and the second pass counts up to k - 1 survivors in O(n) each.

    Edge cases

    • k = 2: the classic majority, but with no promise that it exists.
    • No value passes, as in [1, 2, 3, 4] with k = 2: [].
    • k larger than n: n/k is 0, so every value that appears passes.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> findElements(int[] arr, int k) {
            Map<Integer, Integer> cand = new HashMap<>();   // at most k - 1 candidates with their vote counts
            for (int v : arr) {
                if (cand.containsKey(v)) {
                    cand.put(v, cand.get(v) + 1);
                } else if (cand.size() < k - 1) {
                    cand.put(v, 1);
                } else {                            // v cancels one vote from every candidate
                    Iterator<Map.Entry<Integer, Integer>> it = cand.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<Integer, Integer> e = it.next();
                        if (e.getValue() == 1) it.remove();
                        else e.setValue(e.getValue() - 1);
                    }
                }
            }
            List<Integer> result = new ArrayList<>();
            for (int c : cand.keySet()) {           // second pass: check the real count of each candidate
                int count = 0;
                for (int v : arr) {
                    if (v == c) count++;
                }
                if (count > arr.length / k) result.add(c);
            }
            Collections.sort(result);
            return result;
        }
    }

    C++

    class Solution {
    public:
        vector<int> findElements(vector<int>& arr, int k) {
            map<int, int> cand;                     // at most k - 1 candidates with their vote counts
            for (int v : arr) {
                if (cand.count(v)) {
                    cand[v]++;
                } else if (static_cast<int>(cand.size()) < k - 1) {
                    cand[v] = 1;
                } else {                            // v cancels one vote from every candidate
                    for (auto it = cand.begin(); it != cand.end();) {
                        if (--(it->second) == 0) it = cand.erase(it);
                        else ++it;
                    }
                }
            }
            vector<int> result;
            int n = static_cast<int>(arr.size());
            for (const auto& entry : cand) {        // second pass: check the real count of each candidate
                int count = 0;
                for (int v : arr) {
                    if (v == entry.first) count++;
                }
                if (count > n / k) result.push_back(entry.first);
            }
            sort(result.begin(), result.end());
            return result;
        }
    };

    Python

    class Solution:
        def findElements(self, arr: list[int], k: int) -> list[int]:
            cand = {}                               # at most k - 1 candidates with their vote counts
            for v in arr:
                if v in cand:
                    cand[v] += 1
                elif len(cand) < k - 1:
                    cand[v] = 1
                else:                               # v cancels one vote from every candidate
                    for c in list(cand):
                        cand[c] -= 1
                        if cand[c] == 0:
                            del cand[c]
            # second pass: check the real count of each candidate
            return sorted(c for c in cand if arr.count(c) > len(arr) // k)

    Common mistakes

    • Keeping k candidates instead of k - 1.
    • Forgetting the second pass, which reports values that only survived by luck.
    • Removing entries from a map while looping over it in a way the language does not allow. Use an iterator or a copy of the keys.

    Similar problems