Given an array of integers, find the most occurring element of the array and return any one of its indexes randomly with equal probability.
Examples:
Input:
arr[] = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9]
Output:
Element with maximum frequency present at index 6
OR
Element with maximum frequency present at Index 3
OR
Element with maximum frequency present at index 4
OR
Element with maximum frequency present at index 12
All outputs above have equal probability.
The idea is to iterate through the array once and find out the maximum occurring element and its frequency n. Then we generate a random number r between 1 and n and finally return the r’th occurrence of maximum occurring element in the array.
Below are implementation of above idea –
C++
#include <iostream>
#include <unordered_map>
#include <climits>
using namespace std;
void findRandomIndexOfMax( int arr[], int n)
{
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++)
freq[arr[i]] += 1;
int max_element;
int max_so_far = INT_MIN;
for (pair< int , int > p : freq)
{
if (p.second > max_so_far)
{
max_so_far = p.second;
max_element = p.first;
}
}
int r = ( rand () % max_so_far) + 1;
for ( int i = 0, count = 0; i < n; i++)
{
if (arr[i] == max_element)
count++;
if (count == r)
{
cout << "Element with maximum frequency present "
"at index " << i << endl;
break ;
}
}
}
int main()
{
int arr[] = { -1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5,
7, 8, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
srand ( time (NULL));
findRandomIndexOfMax(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void findRandomIndexOfMax( int arr[], int n)
{
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++)
if (mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1 );
}
else
{
mp.put(arr[i], 1 );
}
int max_element = Integer.MIN_VALUE;
int max_so_far = Integer.MIN_VALUE;
for (Map.Entry<Integer, Integer> p : mp.entrySet())
{
if (p.getValue() > max_so_far)
{
max_so_far = p.getValue();
max_element = p.getKey();
}
}
int r = ( int ) (( new Random().nextInt(max_so_far) % max_so_far) + 1 );
for ( int i = 0 , count = 0 ; i < n; i++)
{
if (arr[i] == max_element)
count++;
if (count == r)
{
System.out.print( "Element with maximum frequency present "
+ "at index " + i + "\n" );
break ;
}
}
}
public static void main(String[] args)
{
int arr[] = { - 1 , 4 , 9 , 7 , 7 , 2 , 7 , 3 , 0 , 9 , 6 , 5 ,
7 , 8 , 9 };
int n = arr.length;
findRandomIndexOfMax(arr, n);
}
}
|
Python3
import random
def findRandomIndexOfMax(arr, n):
mp = dict ()
for i in range (n) :
if (arr[i] in mp):
mp[arr[i]] = mp[arr[i]] + 1
else :
mp[arr[i]] = 1
max_element = - 323567
max_so_far = - 323567
for p in mp :
if (mp[p] > max_so_far):
max_so_far = mp[p]
max_element = p
r = int ( ((random.randrange( 1 , max_so_far, 2 ) % max_so_far) + 1 ))
i = 0
count = 0
while ( i < n ):
if (arr[i] = = max_element):
count = count + 1
if (count = = r):
print ( "Element with maximum frequency present at index " , i )
break
i = i + 1
arr = [ - 1 , 4 , 9 , 7 , 7 , 2 , 7 , 3 , 0 , 9 , 6 , 5 , 7 , 8 , 9 ]
n = len (arr)
findRandomIndexOfMax(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void findRandomIndexOfMax( int [] arr, int n)
{
Dictionary< int , int > mp = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
if (mp.ContainsKey(arr[i]))
{
mp[arr[i]]++;
}
else
{
mp[arr[i]] = 1;
}
}
int max_element = int .MinValue;
int max_so_far = int .MinValue;
foreach (KeyValuePair< int , int > p in mp)
{
if (p.Value > max_so_far)
{
max_so_far = p.Value;
max_element = p.Key;
}
}
Random rand = new Random();
int r = rand.Next(max_so_far) + 1;
for ( int i = 0, count = 0; i < n; i++)
{
if (arr[i] == max_element)
count++;
if (count == r)
{
Console.WriteLine( "Element with maximum frequency present "
+ "at index " + i + "\n" );
break ;
}
}
}
public static void Main()
{
int [] arr = { -1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5,
7, 8, 9 };
int n = arr.Length;
findRandomIndexOfMax(arr, n);
}
}
|
Javascript
<script>
function findRandomIndexOfMax(arr,n)
{
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);
}
let max_element = Number.MIN_VALUE;
let max_so_far = Number.MIN_VALUE;
for (let [key, value] of mp.entries())
{
if (value > max_so_far)
{
max_so_far = value;
max_element = key;
}
}
let r = Math.floor(((Math.random() * max_so_far)% max_so_far)+ 1)
for (let i = 0, count = 0; i < n; i++)
{
if (arr[i] == max_element)
count++;
if (count == r)
{
document.write( "Element with maximum frequency present "
+ "at index " + i + "<br>" );
break ;
}
}
}
let arr=[-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5,
7, 8, 9 ];
let n = arr.length;
findRandomIndexOfMax(arr, n);
</script>
|
Output:
Element with maximum frequency present at index 4
Time complexity of above solution is O(n).
Auxiliary space used by the program is O(n).
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
16 Mar, 2023
Like Article
Save Article