2190. Most Frequent Number Following Key In an Array

problem

solution

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

return target;

}
};

analysis

  • time complexity O(n)
  • space complexity O(n)