2832. Find the Longest Equal Subarray
My accepted Python solution to LeetCode problem 2832, Find the Longest Equal Subarray, running in 366ms.
- Difficulty: Medium
- Python
- Runtime 366ms
- Memory 36.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 366ms, memory 36.6MB, accepted 2025-12-31.
class Solution:
def longestEqualSubarray(self, nums: List[int], k: int) -> int:
from collections import defaultdict
# For each value, store the indices where it appears
indices = defaultdict(list)
for i, num in enumerate(nums):
indices[num].append(i)
result = 0
# For each unique value, find longest equal subarray
for num, idx_list in indices.items():
# Sliding window: count of elements to delete between idx_list[left] and idx_list[right]
# elements to delete = (idx_list[right] - idx_list[left] + 1) - (right - left + 1)
left = 0
for right in range(len(idx_list)):
# While we need to delete more than k elements
while idx_list[right] - idx_list[left] - (right - left) > k:
left += 1
result = max(result, right - left + 1)
return result