Skip to main content
Back to problems
#2958
Medium Algorithms

Length of longest subarray with at most k frequency

Array Hash Table Sliding Window
56.4% acceptance
Feb 25, 2026
1179
36
You are given an integer array nums and an integer k. The frequency of an element x is the number of times it occurs in an array. An array is called good if the frequency of each element in this array is less than or equal to k. Return the length of the longest good subarray of nums.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_subarray_length(nums: Vec<i32>, k: i32) -> i32 {
    use std::collections::HashMap;
    let mut freq: HashMap<i32, i32> = HashMap::new();
    let mut left = 0usize;
    let mut ans = 0i32;
    for right in 0..nums.len() {
      let e = freq.entry(nums[right]).or_insert(0);
      *e += 1;
      while *freq.get(&nums[right]).unwrap() > k {
        *freq.get_mut(&nums[left]).unwrap() -= 1;
        left += 1;
      }
      ans = ans.max((right - left + 1) as i32);
    }
    ans
  }
}