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] == key and,
  • 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
Most Frequent Number Following KeyInput:11002001100key = 1Key 1 found at positions 0 and 3Following elements: 100 (twice), so count = 2Result: 100
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
Asked in
Google 15 Amazon 12 Microsoft 8
32.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen