Leetcode 2190. Most Frequent Number Following Key In an Array
You are given an integer array nums
and an integer key
, which is present in nums
.
For every unique integer target
such that key
is followed immediately by target
in the array nums
, count the number of occurrences of target
in this context, and return the target with the maximum count. If there are multiple targets with the same maximum count, return the smallest one.
key
.key
, increment the count of the next element in the map.import java.util.HashMap;
import java.util.Map;
public class Solution {
public int mostFrequent(int[] nums, int key) {
// Map to store the target numbers and their respective counts
Map<Integer, Integer> targetCount = new HashMap<>();
// Iterate through the array to find key and count the following target numbers
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == key) {
int target = nums[i + 1];
targetCount.put(target, targetCount.getOrDefault(target, 0) + 1);
}
}
// Find the target with the maximum count
int mostFrequentTarget = -1;
int maxCount = 0;
for (Map.Entry<Integer, Integer> entry : targetCount.entrySet()) {
int target = entry.getKey();
int count = entry.getValue();
if (count > maxCount || (count == maxCount && target < mostFrequentTarget)) {
mostFrequentTarget = target;
maxCount = count;
}
}
return mostFrequentTarget;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 100, 2, 200, 1, 100};
int key = 1;
System.out.println(sol.mostFrequent(nums, key)); // Output: 100
}
}
Time Complexity: O(n), where n is the length of the array nums
. We iterate through the array once to build the map and once more to find the target with the maximum count.
Space Complexity: O(t), where t is the number of unique targets that follow the key in the array. This space is used for storing the target counts in the map.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?