Find the Longest Equal Subarray - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,2,2,1], k = 2
Output: 3
💡 Note: We can focus on element 1 which appears at positions [0,1,4]. To make subarray from index 0 to 4 all equal to 1, we need to delete the 2 elements at positions 2 and 3. Since 2 ≤ k, we can achieve a length of 3.
Example 2 — No Deletions Needed
$ Input: nums = [1,1,1,1], k = 1
Output: 4
💡 Note: All elements are already equal, so no deletions needed. The longest equal subarray has length 4.
Example 3 — Limited Deletions
$ Input: nums = [1,2,1], k = 0
Output: 1
💡 Note: With k=0, we cannot delete any elements. The longest equal subarray is any single element, with length 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ nums.length
  • 0 ≤ k ≤ nums.length

Visualization

Tap to expand
Find Longest Equal Subarray: [1,1,2,2,1], k=2Input:11221k = 2Strategy:Focus on element 1 at positions [0,1,4]Window: delete 2 elements to keep 3Result:111Length = 3Maximum length of equal subarray after ≤k deletions
Understanding the Visualization
1
Input Array
Array [1,1,2,2,1] with k=2 deletions allowed
2
Process
Focus on element 1, find longest window needing ≤k deletions
3
Output
Maximum length achievable is 3
Key Takeaway
🎯 Key Insight: Use sliding window on positions of each unique element to efficiently find the longest achievable equal subarray
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen