VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-index-maximum-occurring-element-equal-probability/

⇱ Find an index of maximum occurring element with equal probability - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find an index of maximum occurring element with equal probability

Last Updated : 16 Mar, 2023

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 – 
 

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

Comment
Article Tags:
Article Tags: