Question:
Consider you have an integer array nums of size n, and you want to implement a function to find the index of the most frequent element. If there are multiple elements with the same highest frequency, return the smallest index among them. Which of the following implementations would correctly accomplish this task?
Responses:
A.
int findMostFrequentIndex(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
int maxCount = 0;
int resultIndex = -1;
for (int i = 0; i < nums.length; i++) {
int count = countMap.get(nums[i]);
if (count > maxCount || (count == maxCount && i < resultIndex)) {
maxCount = count;
resultIndex = i;
}
}
return resultIndex;
}
B.
int findMostFrequentIndex(int[] nums) {
Map<Integer, Integer> frequency = new HashMap<>();
for (int num : nums) {
frequency.put(num, frequency.getOrDefault(num, 1) + 1);
}
int index = 0;
for (int i = 1; i < nums.length; i++) {
if (frequency.get(nums[i]) > frequency.get(nums[index])) {
index = i;
}
}
return index;
}
C.
int findMostFrequentIndex(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
int maxIndex = -1, maxCount = 0;
for (int i = 0; i < nums.length; i++) {
int count = countMap.getOrDefault(nums[i], 0) + 1;
countMap.put(nums[i], count);
if (count > maxCount) {
maxCount = count;
maxIndex = i;
}
}
return maxIndex;
}
D. Correct Response
int findMostFrequentIndex(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
Map<Integer, Integer> firstIndexMap = new HashMap<>();
int maxCount = 0;
int resultIndex = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
countMap.put(nums[i], countMap.getOrDefault(nums[i], 0) + 1);
firstIndexMap.putIfAbsent(nums[i], i);
int currentCount = countMap.get(nums[i]);
if (currentCount > maxCount || (currentCount == maxCount && firstIndexMap.get(nums[i]) < resultIndex)) {
maxCount = currentCount;
resultIndex = firstIndexMap.get(nums[i]);
}
}
return resultIndex == Integer.MAX_VALUE ? -1 : resultIndex;
}
Explanation of the correct answer:
Option D is correct because it uses two HashMaps: one (countMap) to keep track of the frequency of each element and another (firstIndexMap) to store the first index at which an element appears. Throughout the loop, it updates the maxCount and checks if the current element's count is either greater than maxCount or equal to maxCount but with a smaller index (using firstIndexMap). This ensures that if multiple elements share the highest frequency, the index of the first occurrence of the most frequent element is returned, satisfying the requirement.
Tip:
Always consider edge cases such as multiple elements having the same frequency and needing to return the smallest index among them when dealing with frequency-based problems. Utilizing additional data structures to track indices alongside frequencies can provide a straightforward solution.