![]() |
VOOZH | about |
Given an array arr[] consisting of n integers, find all the array elements which occurs more than floor(n/3) times.
Note: The returned array of majority elements should be sorted.
Examples:
Input: arr[] = [2, 2, 3, 1, 3, 2, 1, 1]
Output: [1, 2]
Explanation: The frequency of 1 and 2 is 3, which is more than floor n/3 (8/3 = 2).Input: arr[] = [-5, 3, -5]
Output: [-5]
Explanation: The frequency of -5 is 2, which is more than floor n/3 (3/3 = 1).Input: arr[] = [3, 2, 2, 4, 1, 4]
Output: [ ]
Explanation: There is no majority element.
Table of Content
The idea is to iterate over all elements and count the frequency of the element in the array. If the frequency of the element is greater than floor(n/3), add it to the result. To avoid adding duplicate elements into the result, we can check if the element is already present in the result. We can stop the iteration if we have already found two majority elements.
1 2
Note : We can also solve this problem by sorting and then doing a single traversal. This would solve the problem in O(n Log n) time. Another approach can be to count frequencies using hashing. This would work in linear time, but requires O(n) extra space. The below approach solves in linear time and constant extra space.
The idea is based on the observation that there can be at most two majority elements, which appear more than n/3 times. As we iterate the array, We identify potential majority elements by keeping track of two candidates and their respective counts.
Steps:
Since any element than appears more than floor(n/3) times, will dominate over elements that appear less frequently. Whenever we encounter a different element, we decrement the count of both the candidates. This maintains at most two candidates in the array.
1 2