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 the Longest Equal Subarray INPUT nums array: 1 i=0 1 i=1 2 i=2 2 i=3 1 i=4 k = 2 (max deletions) Elements with value 1: 1 1 1 at indices [0, 1, 4] ALGORITHM STEPS 1 Group by Value Store indices for each value 2 Sliding Window For each group of indices 3 Count Deletions deletions = window_len - count 4 Shrink if Needed If deletions > k, move left Window on value 1 indices: indices[1] = [0, 1, 4] 0 1 4 window: idx[4] - idx[0] + 1 = 5 count of 1s = 3 deletions = 5 - 3 = 2 2 <= k, valid! max = 3 FINAL RESULT Longest equal subarray after deletion: 1 1 2 2 1 Delete 2 elements (crossed out) Resulting equal subarray: 1 1 1 Output: 3 OK - Verified 3 ones, 2 deletions used Key Insight: For each unique value, group its indices. Use a sliding window on these indices to find the longest subarray where deletions needed = (rightIdx - leftIdx + 1) - windowSize <= k. Time: O(n), Space: O(n) for storing indices grouped by value. TutorialsPoint - Find the Longest Equal Subarray | Optimal Solution (Sliding Window)
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