Skip to main content
Back to problems
#2831
Medium Algorithms

Find the longest equal subarray

Array Hash Table Binary Search Sliding Window
37.7% acceptance
Feb 25, 2026
756
19
You are given a 0-indexed integer array nums and an integer k. A subarray is called equal if all of its elements are equal. Note that the empty subarray is an equal subarray. Return the length of the longest possible equal subarray after deleting at most k elements from nums. A subarray is a contiguous, possibly empty sequence of elements within an array.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn longest_equal_subarray(nums: Vec<i32>, k: i32) -> i32 {
    use std::collections::HashMap;
    let k = k as usize;
    let mut pos: HashMap<i32, Vec<usize>> = HashMap::new();
    for (i, &v) in nums.iter().enumerate() { pos.entry(v).or_default().push(i); }
    let mut ans = 1usize;
    for indices in pos.values() {
      let m = indices.len();
      let mut l = 0;
      for r in 0..m {
        // deletions needed = (indices[r] - indices[l] + 1) - (r - l + 1)
        while indices[r] - indices[l] - (r - l) > k { l += 1; }
        ans = ans.max(r - l + 1);
      }
    }
    ans as i32
  }
}