For people who want to understand what this algorithm does and why it works: see my detailed answer .
Here I will describe the natural continuation of this algorithm (or generalization). Thus, in the algorithm of the standard majority of votes, you should find an element that appears in the stream at least n/2 times, where n is the size of the stream. You can do this in O(n) time (with a tiny constant and in O(log(n)) space, the worst case and unlikely.
The generalized algorithm allows you to find the k most common elements, where each time in the original stream appeared at least n/(k+1) times. Please note that if k = 1, you get your original problem.
The solution to this problem is really similar to the original one, with the exception of one counter and one possible element, you support k counters and k possible elements. Now the logic goes the same way. You iterate over the array and, if the element is in possible elements, you increase its counter, if one of the counters is zero - replace the element of this counter with a new element. Otherwise, simply decrease the values.
As with the original majority-vote algorithm, you need to have a guarantee that you have these elements of the majority majority, otherwise you will have to make another pass through the array to make sure that your previously found possible elements are correct. Here is my python attempt (did not go through rigorous testing).
from collections import defaultdict def majority_element_general(arr, k=1): counter, i = defaultdict(int), 0 while len(counter) < k and i < len(arr): counter[arr[i]] += 1 i += 1 for i in arr[i:]: if i in counter: counter[i] += 1 elif len(counter) < k: counter[i] = 1 else: fields_to_remove = [] for el in counter: if counter[el] > 1: counter[el] -= 1 else: fields_to_remove.append(el) for el in fields_to_remove: del counter[el] potential_elements = counter.keys()
source share