VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-all-array-elements-occurring-more-than-floor-of-n-divided-by-3-times/

⇱ Majority Element II - Elements occurring more than ⌊n/3⌋ times - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Majority Element II - Elements occurring more than ⌊n/3⌋ times

Last Updated : 28 Mar, 2026

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.

[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space

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.


Output
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.

[Expected Approach] Boyer-Moore’s Voting Algorithm - O(n) Time and O(1) 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:

  • Initialize two variables ele1 = -1 and ele2 = -1, for candidates and two variables cnt1 = 0 and cnt2 = 0, for counting.
  • In each iteration,
    • If an element is equal to any candidate, update that candidate's count.
    • If count of a candidate reaches zero then replace that candidate with current element.
    • If neither candidate matches and both counts are non zero, decrement the counts.
  • After this, in second pass we check if the chosen candidates appear more than n/3 times in the array. If they do then include them in result array.

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.



Output
1 2 


Comment
Article Tags: