Given a non-empty integer array, find the index of the maximum occurring element with an equal probability.

For example, consider the input: {4, 3, 6, 8, 4, 6, 2, 4, 5, 9, 7, 4}. The maximum occurring element, 4, occurs at index 0, 4, 7, and 11. The solution should return any one of these indices with an equal probability. If there are two maximum occurring elements in the array, the solution should consider the first occurring maximum element.

Practice this problem

The problem looks complicated at first look but has a straightforward solution. Following is the algorithm:

  1. Store the count of each element of the input in a map.
  2. Traverse the map and find the first maximum occurring element.
  3. Generate a random number k between 1 and the count of the maximum occurring element.
  4. Traverse the input and return the index of the k'th occurrence of the maximum occurring element.

Following is the C++, Java, and Python implementation of the algorithm:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output (will vary):
 
The index of the maximum occurring element is 11
The index of the maximum occurring element is 4
The index of the maximum occurring element is 11
The index of the maximum occurring element is 0
The index of the maximum occurring element is 7

The time complexity of the proposed solution is O(n), where n is the input size and requires O(n) extra space for the map.