[LeetCode] Most Frequent Number Following Key In an Array

2190. Most Frequent Number Following Key In an Array

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 <= n - 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int mostFrequent(vector<int>& nums, int key) {
unordered_map<int, int> counter;
for(int i = 0; i < nums.size() - 1; i++) {
if(nums[i] == key) {
counter[nums[i+1]]++;
}
}
int res = -1, cnt = -1;
for(auto [target, count] : counter) {
if(cnt < count) {
cnt = count;
res = target;
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/06/PS/LeetCode/most-frequent-number-following-key-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.