Skip to content

2190. Most Frequent Number Following Key In an Array

  • Time: $O(n)$
  • Space: $O(1001) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int mostFrequent(vector<int>& nums, int key) {
    vector<int> count(1001);

    for (int i = 0; i + 1 < nums.size(); ++i)
      if (nums[i] == key)
        ++count[nums[i + 1]];

    return ranges::max_element(count) - count.begin();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int mostFrequent(int[] nums, int key) {
    int[] count = new int[1001];
    int ans = 0;

    for (int i = 0; i + 1 < nums.length; ++i)
      if (nums[i] == key)
        ++count[nums[i + 1]];

    for (int i = 1; i < 1001; ++i)
      if (count[i] > count[ans])
        ans = i;

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def mostFrequent(self, nums: list[int], key: int) -> int:
    count = collections.Counter()

    for a, b in itertools.pairwise(nums):
      if a == key:
        count[b] += 1

    return max(count, key=lambda num: count[num])