Most Frequent Number Following Key In an Array - Problem
You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums.
For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that:
0 <= i <= nums.length - 2,nums[i] == keyand,nums[i + 1] == target.
Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,100,200,1,100], key = 1
›
Output:
100
💡 Note:
Key 1 appears at indices 0 and 3. Following elements are 100 (twice) and 100. So 100 appears 2 times after key, which is maximum.
Example 2 — Different Followers
$
Input:
nums = [2,2,2,2,3], key = 2
›
Output:
2
💡 Note:
Key 2 appears at indices 0, 1, 2, 3. Following elements are 2, 2, 2, 3. Element 2 follows key 3 times, element 3 follows once.
Example 3 — Single Occurrence
$
Input:
nums = [1,2,3,4,5], key = 3
›
Output:
4
💡 Note:
Key 3 appears only at index 2. The following element is 4, so 4 has count 1 (maximum).
Constraints
- 2 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 1000
- The test cases will be generated such that key appears in nums and the answer is unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with key occurrences
2
Process
Count elements following key
3
Output
Most frequent follower
Key Takeaway
🎯 Key Insight: Use hash map to count followers of key in single pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code