#2190
Easy Algorithms Most frequent number following key in an array
Array Hash Table Counting
59.4% acceptance
Feb 25, 2026
409
253
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.
Return the target with the maximum count.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn most_frequent(nums: Vec<i32>, key: i32) -> i32 {
let mut count = [0i32; 1001];
for i in 0..nums.len() - 1 {
if nums[i] == key {
count[nums[i + 1] as usize] += 1;
}
}
count.iter().enumerate().max_by_key(|&(_, &c)| c).map(|(i, _)| i as i32).unwrap()
}
}