Find the Longest Equal Subarray - Problem
Find the Longest Equal Subarray

You are given a 0-indexed integer array nums and an integer k representing the maximum number of elements you can delete.

Your goal is to find the longest possible equal subarray after deleting at most k elements from the original array. An equal subarray is one where all elements have the same value.

Key Points:
• A subarray must be contiguous in the final array (after deletions)
• You can delete at most k elements from anywhere in the array
• The empty subarray is considered an equal subarray with length 0
• Elements don't need to be originally adjacent before deletions

Example: Given nums = [1,3,2,3,1,3] and k = 3, you can delete the elements at indices 0, 2, and 4 to get [3,3,3], resulting in an equal subarray of length 3.

Return: The length of the longest possible equal subarray after performing at most k deletions.

Input & Output

example_1.py — Basic case
$ Input: nums = [1,3,2,3,1,3], k = 3
Output: 3
💡 Note: We can delete elements at indices 0, 2, and 4 to get [3,3,3]. This creates an equal subarray of length 3, which is the maximum possible.
example_2.py — No deletions needed
$ Input: nums = [1,1,2,2,5,5], k = 2
Output: 2
💡 Note: The longest equal subarrays are [1,1], [2,2], or [5,5], each with length 2. No deletions are needed since these are already contiguous equal subarrays.
example_3.py — Single element array
$ Input: nums = [1], k = 0
Output: 1
💡 Note: With only one element, the longest equal subarray has length 1. No deletions are needed or allowed (k=0).

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ nums.length
  • 0 ≤ k ≤ nums.length
  • Follow-up: Can you solve this in O(n) time?

Visualization

Tap to expand
The Pearl Collector's ChallengeOriginal Pearl String:132313Grouped by Colors:Red Pearls (1):Positions: [0, 4]Max length with k=3 deletions: 2Teal Pearls (3): ← WINNERPositions: [1, 3, 5]Span: 5 positions, Need: 2 deletions ≤ k=3 ✓Blue Pearls (2):Positions: [2]Max length: 1🎯 Result: Longest equal string = 3 teal pearls
Understanding the Visualization
1
Sort pearls by color
Group all pearl positions by their color (value)
2
For each color, use sliding window
Find the longest span where deletions ≤ k
3
Track the best result
Return the maximum length found across all colors
Key Takeaway
🎯 Key Insight: Group elements by value and use sliding window on each group's indices. For any window spanning positions [i,j] with c target elements, we need exactly (j-i+1-c) deletions. Find the maximum c where deletions ≤ k.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
28.2K Views
Medium-High Frequency
~25 min Avg. Time
847 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