Problem
Given an array of integers occurring between range[0, n)
where n is length of the array, write a algorithm to find the element which appears maximum number of times in the array.
Examples
Example 1:
|
|
Solution
We have discussed the solutions like nested loops, sorting and hashmap here - Find most frequent element in the array.
As this is special case, we can use array as hashmap, and use array index to track the elements.
[!NOTE] This solution works only if array has positive integers and all the elements in the array are in range from 0 to n-1 where n is the size of the array.
Method 1 - Using Index to track count
Algorithm
Here is the algorithm:
- Navigate the array.
- Update the array as for i’th index :-
nums[nums[i]% n] = nums[nums[i]% n] + n
; - Now navigate the updated array and check which index has the maximum value, that index number is the element which has the maximum occurrence in the array.
- See the picture below for more explanation.
This solution is similar to Check if Array is Consecutive Integers.
Code
|
|
Complexity
- O(n) - For looping on array twice
- O(1) - As we don’t use any extra space, and reuse array instead