Solution: Majority Element
Solution for the Majority Element Problem.
We'll cover the following
Naive solution
Here is the naive algorithm for solving the Majority Element Problem with quadratic running time:
:
for from to :
0
for from to :
if = :
if :
return
return
In practice, we can scan the input sequence and save the number of occurrences of each element in an associative array. The running time of this solution depends on a particular implementation of an associative array. If it is implemented as a balanced search tree, every lookup in the array will cost and the overall running time will be . For hash tables, the lookups are efficient in practice, though they might vary depending on the input data.
The divide-and-conquer strategy results in a simple algorithm with running time . A simple, but crucial idea: if is a majority element in a sequence, then must be a majority element in at least one of its halves. Note that the converse is not true; both halves of a sequence contain majority elements ( and , respectively), but none of them is a majority element of the original sequence. This leads to the following algorithm: find a majority element recursively in both halves and for each of them check its number of occurrences in the original sequence. For the last step, we need two linear scans that can be performed in time . Therefore, the running time satisfies and therefore, .
Exercise break: Can you design an even faster algorithm? It’s based on the following idea. Partition the input elements into pairs. For each pair, if the two elements are different, discard both of them; otherwise, discard one of them.
Code
The following code implements the divide-and-conquer algorithm discussed above. Note that we are using semiopen intervals for recursive calls.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.