Find all array elements occurring more than ⌊N/3⌋ times
Last Updated :
11 Mar, 2023
Given an array arr[] consisting of N integers, the task is to find all the array elements which occurs more than floor (n/3) times.
Examples:
Input: arr[] = {5, 3, 5}
Output: 5
Explanation:
The frequency of 5 is 2, which is more than N/3(3/3 = 1).
Input: arr[] = {7, 7, 7, 3, 4, 4, 4, 5}
Output: 4 7
Explanation:
The frequency of 7 and 4 in the array is 3, which is more than N/3( 8/3 = 2).
Method 1:
Approach: The basic solution is to have two loops and keep track of the maximum count for all different elements. If maximum count becomes greater than n/3 then print it. If the maximum count doesn’t become more than n/3 after the traversal of array then the majority element doesn’t exists.
C++
#include <bits/stdc++.h>
using namespace std;
void findMajority( int arr[], int n) {
int flag = 0;
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = i; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > (n / 3)) {
cout << arr[i] << " " ;
flag = 1;
}
}
if (!flag)
cout << "No Majority Element" << endl;
}
int main() {
int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
findMajority(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void findMajority( int arr[], int n)
{
int flag= 0 ;
for ( int i = 0 ; i < n; i++) {
int count = 0 ;
for ( int j = i; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
if (count > n/ 3 ) {
System.out.print(arr[i]+ " " );
flag= 1 ;
}
}
if (flag== 0 )
System.out.println( "No Majority Element" );
}
public static void main (String[] args) {
int arr[] = { 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 };
int n = arr.length;
findMajority(arr, n);
}
}
|
Python3
def findMajority(arr, n):
flag = 0
for i in range (n):
count = 0
for j in range (i, n):
if (arr[i] = = arr[j]):
count + = 1
if (count > int (n / 3 )):
print (arr[i], end = " " )
flag = 1
if (flag = = 0 ):
print ( "No Majority Element" )
arr = [ 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 ]
n = len (arr)
findMajority(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void findMajority( int [] arr, int n)
{
int flag = 0;
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = i; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
if (count > n/3) {
Console.Write(arr[i] + " " );
flag = 1;
}
}
if (flag == 0)
Console.Write( "No Majority Element" );
}
static void Main() {
int [] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
int n = arr.Length;
findMajority(arr, n);
}
}
|
Javascript
<script>
function findMajority(arr, n)
{
var flag = 0;
for ( var i = 0; i < n; i++)
{
var count = 0;
for ( var j = i; j < n; j++)
{
if (arr[i] == arr[j])
count++;
}
if (count > n / 3)
{
document.write(arr[i] + " " );
flag = 1;
}
}
if (flag == 0)
{
document.write( "No Majority Element" );
}
}
var arr = [ 2, 2, 3, 1, 3, 2, 1, 1 ];
var n = arr.length;
findMajority(arr, n);
</script>
|
Complexity Analysis:
- Time Complexity: O(n*n) A nested loop is needed where both the loops traverse the array from start to end, so the time complexity is O(n^2).
- Auxiliary Space: O(1) As no extra space is required for any operation so the space complexity is constant.
Method 2 (Using Hashmap):
- Approach: This method is somewhat similar to Moore voting algorithm in terms of time complexity, but in this case, there is no need for the second step of Moore voting algorithm. But as usual, here space complexity becomes O(n).
In Hashmap(key-value pair), at value, maintain a count for each element(key) and whenever the count is greater than half of the array length, return that key(majority element).
C++
#include <bits/stdc++.h>
using namespace std;
void findMajority( int arr[], int size)
{
unordered_map< int , int > m;
for ( int i = 0; i < size; i++)
m[arr[i]]++;
int flag = 0;
for ( auto i : m)
{
if (i.second > size / 3)
{
flag =1;
cout << i.first << " " ;
}
}
if (flag == 0)
cout << "No Majority element" << endl;
}
int main()
{
int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1};
int n = sizeof (arr) / sizeof (arr[0]);
findMajority(arr, n);
return 0;
}
|
Java
import java.util.HashMap;
class MajorityElement
{
private static void findMajority( int [] arr)
{
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
int flag= 0 ;
for ( int i = 0 ; i < arr.length; i++) {
if (map.containsKey(arr[i])) {
int count = map.get(arr[i]) + 1 ;
if (count > arr.length / 3 ) {
System.out.print(arr[i]+ " " );
flag= 1 ;
} else
map.put(arr[i], count);
}
else
map.put(arr[i], 1 );
}
if (flag== 0 )
System.out.println( " No Majority element" );
}
public static void main(String[] args)
{
int a[] = new int []{ 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 };
findMajority(a);
}
}
|
Python3
def findMajority(arr, size):
m = {}
for i in range (size):
if arr[i] in m:
m[arr[i]] + = 1
else :
m[arr[i]] = 1
flag = 0
for i in sorted (m):
if m[i] > int (size / 3 ):
flag = 1
print (i, end = " " )
if flag = = 0 :
print ( "No Majority element" )
arr = [ 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 ]
n = len (arr)
findMajority(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void findMajority( int [] arr, int size)
{
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < size; i++)
{
if (m.ContainsKey(arr[i]))
{
m[arr[i]]++;
}
else {
m[arr[i]] = 1;
}
}
int flag = 0;
List< int > ans = new List< int >();
foreach (KeyValuePair< int , int > i in m)
{
if (i.Value > size / 3)
{
flag =1;
ans.Add(i.Key);
}
}
if (ans.Count > 0)
{
ans.Sort();
for ( int i = 0; i < ans.Count; i++)
{
Console.Write(ans[i] + " " );
}
}
if (flag == 0)
Console.WriteLine( "No Majority element" );
}
static void Main() {
int [] arr = { 2, 2, 3, 1, 3, 2, 1, 1};
int n = arr.Length;
findMajority(arr, n);
}
}
|
Javascript
<script>
function findMajority(arr, size)
{
let m = new Map();
for (let i = 0; i < size; i++)
{
if (m.has(arr[i]) == true ){
m.set(arr[i], m.get(arr[i]) + 1);
}
else m.set(arr[i], 1);
}
let flag = 0;
for (let [key, value] of m)
{
if (value > size / 3)
{
flag = 1;
document.write(key, " " );
}
}
if (flag == 0)
document.write( "No Majority element" , "</br>" );
}
let arr = [ 2, 2, 3, 1, 3, 2, 1, 1 ];
let n = arr.length;
findMajority(arr, n);
</script>
|
Complexity Analysis:
- Time Complexity: O(n) One traversal of the array is needed, so the time complexity is linear.
- Auxiliary Space: O(n) Since a hashmap requires linear space.
Method 3 (Moore’s Voting algorithm):
The idea is based on Moore’s Voting algorithm. We first find two candidates. Then we check if any of these two candidates is actually a majority. Below is the solution for above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void findMajority( int arr[], int n){
int count1 = 0, count2 = 0;
int first=INT_MAX, second=INT_MAX;
int flag=0;
for ( int i = 0; i < n; i++) {
if (first == arr[i])
count1++;
else if (second == arr[i])
count2++;
else if (count1 == 0) {
count1++;
first = arr[i];
}
else if (count2 == 0) {
count2++;
second = arr[i];
}
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == first)
count1++;
else if (arr[i] == second)
count2++;
}
if (count1 > n / 3){
cout << first << " " ;
flag=1;
}
if (count2 > n / 3){
cout << second << " " ;
flag=1;
}
if (flag==0){
cout << "No Majority Element" << endl;
}
}
int main() {
int arr[] = { 2, 2, 3, 1, 3, 2, 1, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
findMajority(arr, n);
return 0;
}
|
Java
class GFG {
static void findMajority( int arr[], int n)
{
int count1 = 0 , count2 = 0 ;
int flag= 0 ;
int first = Integer.MIN_VALUE;;
int second = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++) {
if (first == arr[i])
count1++;
else if (second == arr[i])
count2++;
else if (count1 == 0 ) {
count1++;
first = arr[i];
}
else if (count2 == 0 ) {
count2++;
second = arr[i];
}
else {
count1--;
count2--;
}
}
count1 = 0 ;
count2 = 0 ;
for ( int i = 0 ; i < n; i++) {
if (arr[i] == first)
count1++;
else if (arr[i] == second)
count2++;
}
if (count1 > n / 3 ){
System.out.print(first+ " " );
flag= 1 ;
}
if (count2 > n / 3 ){
System.out.print(second+ " " );
flag= 1 ;
}
if (flag== 0 )
System.out.println( "No Majority Element" );
}
public static void main(String args[])
{
int arr[] = { 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 };
int n = arr.length;
findMajority(arr,n);
}
}
|
Python3
def findMajority(arr, n):
count1 = 0
count2 = 0
first = 2147483647
second = 2147483647
flag = 0
for i in range (n):
if first = = arr[i]:
count1 + = 1
elif second = = arr[i]:
count2 + = 1
elif count1 = = 0 :
count1 + = 1
first = arr[i]
elif count2 = = 0 :
count2 + = 1
second = arr[i]
else :
count1 - = 1
count2 - = 1
count1 = 0
count2 = 0
for i in range (n):
if arr[i] = = first:
count1 + = 1
elif arr[i] = = second:
count2 + = 1
if count1 > int (n / 3 ):
print (first, end = " " )
flag = 1
if count2 > int (n / 3 ):
print (second, end = " " )
flag = 1
if flag = = 0 :
print ( "No Majority Element" )
arr = [ 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 ]
n = len (arr)
findMajority(arr, n)
|
C#
using System;
class GFG {
static void findMajority( int [] arr, int n)
{
int count1 = 0, count2 = 0;
int flag = 0;
int first = Int32.MinValue;
int second = Int32.MaxValue;
for ( int i = 0; i < n; i++)
{
if (first == arr[i])
count1++;
else if (second == arr[i])
count2++;
else if (count1 == 0) {
count1++;
first = arr[i];
}
else if (count2 == 0) {
count2++;
second = arr[i];
}
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == first)
count1++;
else if (arr[i] == second)
count2++;
}
if (count1 > n / 3){
Console.Write(first+ " " );
flag=1;
}
if (count2 > n / 3){
Console.Write(second+ " " );
flag=1;
}
if (flag==0)
Console.Write( "No Majority Element" );
}
static void Main() {
int [] arr = { 2, 2, 3, 1, 3, 2, 1, 1 };
int n = arr.Length;
findMajority(arr,n);
}
}
|
Javascript
<script>
function findMajority(arr, n) {
var count1 = 0,
count2 = 0;
var first = 2147483647,
second = 2147483647;
var flag = 0;
for ( var i = 0; i < n; i++) {
if (first === arr[i]) count1++;
else if (second === arr[i]) count2++;
else if (count1 === 0) {
count1++;
first = arr[i];
} else if (count2 === 0) {
count2++;
second = arr[i];
}
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for ( var i = 0; i < n; i++) {
if (arr[i] === first) count1++;
else if (arr[i] === second) count2++;
}
if (count1 > n / 3) {
document.write(first + " " );
flag = 1;
}
if (count2 > n / 3) {
document.write(second + " " );
flag = 1;
}
if (flag === 0) {
document.write( "No Majority Element" + "<br>" );
}
}
var arr = [2, 2, 3, 1, 3, 2, 1, 1];
var n = arr.length;
findMajority(arr, n);
</script>
|
Complexity Analysis:
- Time Complexity: O(n) First pass of the algorithm takes complete traversal over the array contributing to O(n) and another O(n) is consumed in checking if count1 and count2 is greater than floor(n/3) times.
- Auxiliary Space: O(1) As no extra space is required so space complexity is constant
Method 4:
Approach: To solve the problem, the idea is to use Divide and Conquer technique. Follow the steps below to solve the problem:
- Initialize a function majorityElement() that will return the count of majority element in the array from any index left to right.
- Divide the given array arr[] into two halves and repeatedly pass it to the function majorityElement().
- Initialize low and high as 0 and (N – 1) respectively.
- Compute the majority element using the following steps:
- If low = high: Return arr[low] as the majority element.
- Find the middle index,say mid(= (low + high)/2).
- Recursively call for both the left and right subarrays as majorityElement(arr, low, mid) and majorityElement(arr, mid + 1, high).
- After completing the above steps, merge both the subarrays and return the majority element.
- Whenever the required majority element is found, append it to the resultant list.
- Print all the majority elements stored in the list.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > divideAndConquer( int lo, int hi, int a[])
{
if (lo == hi) {
vector< int > ans{ a[lo] };
return ans;
}
int mid = lo + (hi - lo) / 2;
vector< int > left = divideAndConquer(lo, mid, a);
vector< int > right = divideAndConquer(mid + 1, hi, a);
vector< int > result;
for ( auto it : left) {
for ( auto itr : right) {
bool flag = 0;
if (it == itr) {
flag = 1;
break ;
}
if (!flag)
result.push_back(it);
}
}
for ( auto it : right)
result.push_back(it);
vector< int > ans;
for ( auto it : result) {
int count = 0;
for ( int i = lo; i <= hi; i++)
if (a[i] == it)
count += 1;
if (count > (hi - lo + 1) / 3)
ans.push_back(it);
}
return ans;
}
void majorityElement( int a[], int n)
{
if (n == 0)
return ;
vector< int > ans = divideAndConquer(0, n - 1, a);
for ( auto it : ans) {
cout << it << " " ;
}
}
int main()
{
int a[] = { 7, 7, 7, 3, 4, 4, 4, 6 };
majorityElement(a, 8);
}
|
Java
import java.util.*;
class GFG {
static ArrayList<Integer>
divideAndConquer( int lo, int hi, int [] a)
{
if (lo == hi) {
ArrayList<Integer> ans_
= new ArrayList<Integer>();
ans_.add(a[lo]);
return ans_;
}
int mid = lo + (hi - lo) / 2 ;
ArrayList<Integer> left
= divideAndConquer(lo, mid, a);
ArrayList<Integer> right
= divideAndConquer(mid + 1 , hi, a);
ArrayList<Integer> result
= new ArrayList<Integer>();
for (var it : left) {
for (var itr : right) {
boolean flag = false ;
if (it == itr) {
flag = true ;
break ;
}
if (!flag)
result.add(it);
}
}
for (var it : right)
result.add(it);
ArrayList<Integer> ans = new ArrayList<Integer>();
for (var it : result) {
int count = 0 ;
for ( int i = lo; i <= hi; i++)
if (a[i] == it)
count += 1 ;
if (count > (hi - lo + 1 ) / 3 )
ans.add(it);
}
return ans;
}
static void majorityElement( int [] a, int n)
{
if (n == 0 )
return ;
ArrayList<Integer> res
= divideAndConquer( 0 , n - 1 , a);
for (var it : res) {
System.out.print(it + " " );
}
}
public static void main(String[] args)
{
int [] a = { 7 , 7 , 7 , 3 , 4 , 4 , 4 , 6 };
majorityElement(a, 8 );
}
}
|
Python3
class Solution:
def majorityElement( self , a):
if not a:
return []
def divideAndConquer(lo, hi):
if lo = = hi:
return [a[lo]]
mid = lo + (hi - lo) / / 2
left = divideAndConquer(lo, mid)
right = divideAndConquer(mid + 1 , hi)
result = []
for numbers in left:
if numbers not in right:
result.append(numbers)
result.extend(right)
ans = []
for number in result:
count = 0
for index in range (lo, hi + 1 ):
if a[index] = = number:
count + = 1
if count > (hi - lo + 1 ) / / 3 :
ans.append(number)
return ans
print (divideAndConquer( 0 , len (a) - 1 ))
if __name__ = = "__main__" :
a = [ 7 , 7 , 7 , 3 , 4 , 4 , 4 , 6 ]
object = Solution()
object .majorityElement(a)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static List< int > divideAndConquer( int lo, int hi, int [] a)
{
if (lo == hi) {
List< int > ans_ = new List< int >();
ans_.Add(a[lo]);
return ans_;
}
int mid = lo + (hi - lo) / 2;
List< int > left = divideAndConquer(lo, mid, a);
List< int > right = divideAndConquer(mid + 1, hi, a);
List< int > result = new List< int >();
foreach ( var it in left) {
foreach ( var itr in right) {
bool flag = false ;
if (it == itr) {
flag = true ;
break ;
}
if (!flag)
result.Add(it);
}
}
foreach ( var it in right)
result.Add(it);
List< int > ans = new List< int >();
foreach ( var it in result) {
int count = 0;
for ( int i = lo; i <= hi; i++)
if (a[i] == it)
count += 1;
if (count > (hi - lo + 1) / 3)
ans.Add(it);
}
return ans;
}
static void majorityElement( int [] a, int n)
{
if (n == 0)
return ;
List< int > res = divideAndConquer(0, n - 1, a);
foreach ( var it in res) {
Console.Write(it + " " );
}
}
public static void Main( string [] args)
{
int [] a = { 7, 7, 7, 3, 4, 4, 4, 6 };
majorityElement(a, 8);
}
}
|
Javascript
function divideAndConquer( lo, hi, a)
{
if (lo == hi) {
let ans=[];
ans.push(a[hi]);
return ans;
}
let mid = Math.round( (hi + lo) / 2)-1;
let left = divideAndConquer(lo, mid, a);
let right = divideAndConquer(mid + 1, hi, a);
let result = [];
for (let i = 0; i < left.length; i++) {
let it = left[i];
for (let j = 0; j < right.length; j++) {
let itr = right[j];
let flag = false ;
if (it == itr) {
flag = 1;
break ;
}
if (flag == false )
result.push(it);
}
}
for (let i = 0; i < right.length; i++)
result.push(right[i]);
let ans = [];
for (let i = 0; i < result.length; i++) {
let it = result[i];
let count = 0;
for (let i = lo; i <= hi; i++)
if (a[i] == it)
count += 1;
if (count > (hi - lo + 1) / 3)
ans.push(it);
}
return ans;
}
function majorityElement(a, n)
{
if (n == 0)
return ;
let ans = divideAndConquer(0, n - 1, a);
console.log(ans);
}
let a = [ 7, 7, 7, 3, 4, 4, 4, 6 ];
majorityElement(a, 8);
|
Time Complexity: O(N*log N)
Auxiliary Space: O(log N)
Another Approach: Using Built-in Python functions:
- Count the frequencies of every element using Counter() function.
- Traverse the frequency array and print all the elements which occur at more than n/3 times.
Below is the implementation:
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
void printElements( int arr[], int n)
{
int x = n / 3;
unordered_map< int , int > mp;
for ( int i = 0; i < n; i++) {
if (mp.find(arr[i]) == mp.end()) {
mp[arr[i]] = 1;
} else {
mp[arr[i]]++;
}
}
vector< int > result;
for ( auto entry : mp) {
if (entry.second > x) {
result.push_back(entry.first);
}
}
for ( int i = 0; i < result.size(); i++) {
cout << result[i] << " " ;
}
}
int main()
{
int arr[] = { 7, 7, 7, 3, 4, 4, 4, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
printElements(arr, n);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void printElements( int [] arr, int n)
{
int x = n / 3 ;
Map<Integer, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < arr.length; i++) {
if (!mp.containsKey(arr[i])) {
mp.put(arr[i], 1 );
}
else {
mp.put(arr[i], mp.get(arr[i]) + 1 );
}
}
for (Map.Entry<Integer, Integer> entry :
mp.entrySet()) {
if (entry.getValue() > x) {
System.out.print(entry.getKey() + " " );
}
}
}
public static void main(String[] args)
{
int [] arr = { 7 , 7 , 7 , 3 , 4 , 4 , 4 , 6 };
int n = arr.length;
printElements(arr, n);
}
}
|
Python3
from collections import Counter
def printElements(arr, n):
x = n / / 3
mp = Counter(arr)
for it in mp:
if mp[it] > x:
print (it, end = " " )
arr = [ 7 , 7 , 7 , 3 , 4 , 4 , 4 , 6 ]
n = len (arr)
printElements(arr, n)
|
C#
using System;
using System.Collections.Generic;
public class MainClass
{
public static void PrintElements( int [] arr, int n)
{
int x = n / 3;
Dictionary< int , int > dict = new Dictionary< int , int >();
for ( int i = 0; i < arr.Length; i++)
{
if (!dict.ContainsKey(arr[i]))
{
dict.Add(arr[i], 1);
}
else
{
dict[arr[i]] += 1;
}
}
foreach (KeyValuePair< int , int > kvp in dict)
{
if (kvp.Value > x)
{
Console.Write(kvp.Key + " " );
}
}
}
public static void Main()
{
int [] arr = { 7, 7, 7, 3, 4, 4, 4, 6 };
int n = arr.Length;
PrintElements(arr, n);
}
}
|
Javascript
function printElements(arr, n) {
let x = Math.floor(n / 3);
let mp = new Map();
for (let i = 0; i < n; i++) {
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1);
} else {
mp.set(arr[i], 1);
}
}
for (let [key, value] of mp) {
if (value > x) {
console.log(key, end = " " );
}
}
}
let arr = [7, 7, 7, 3, 4, 4, 4, 6];
let n = arr.length;
printElements(arr, n);
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...