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 Key In an Array INPUT Array nums: 1 i=0 100 i=1 200 i=2 1 i=3 100 i=4 Key = 1 (highlighted in red) Input Values: nums = [1,100,200,1,100] key = 1 Find most frequent number immediately after key ALGORITHM STEPS 1 Initialize Hash Map Create empty count map 2 Iterate Array For i = 0 to n-2 3 Check Key Match If nums[i] == key, count nums[i+1] 4 Find Maximum Return target with max count Hash Map (count): Target Count 100 2 200 0 100 appears 2x after key=1 FINAL RESULT Key occurrences in array: 1 --> 100 1 --> 100 100 follows key=1 twice Output: 100 OK - Maximum count = 2 Target 100 is most frequent number following key Key Insight: Use a hash map to count occurrences of each number that immediately follows the key. For each index i where nums[i] == key, increment count for nums[i+1] in the hash map. Time Complexity: O(n) | Space Complexity: O(n) for the hash map storage. TutorialsPoint - Most Frequent Number Following Key In an Array | Hash Approach
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