![]() |
VOOZH | about |
Given an integer array arr[], find the element that appears most frequently. If multiple elements have the same highest frequency, return the largest among them.
Examples:
Input : arr[] = [1, 3, 2, 1, 4, 1]
Output : 1
Explanation: 1 appears three times in array which is maximum frequency.Input : arr[] = [10, 20, 10, 20, 30, 20, 20]
Output : 20 appears four times in array which is maximum frequencyInput: arr[] = [1, 2, 2, 4, 1]
Output: 2
Explanation: 1 and 2 both appear two times, so return 2 as it's value is bigger.
Table of Content
The naive approach involves using two nested loops: the outer loop picks each element, and the inner loop counts the frequency of the picked element. Update if count is higher than current max count or same but value is larger than current value.
30
This approach begins by sorting the array, which groups identical elements together. Once sorted, a linear traversal is performed to count the frequency of each element. Since identical elements appear consecutively after sorting, tracking their frequency becomes straightforward.
30
This approach uses a hash table to count the frequency of each element efficiently. After building the frequency map, the element with the highest frequency is identified and choosing the largest one in case of a tie.
30