↓Skip to main content
  1. LeetCode/

LeetCode 2831: Find the Longest Equal Subarray

·2 mins· ·
LeetCode Medium Sliding-Window Hash-Table Binary-Search Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-01-11

  • Submissions: Wrong Answer → Time Limit Exceeded ×2 → Accepted

Approach
#

What remains is copies of one value v. Handle each value separately:

  • List the positions where v appears, pos = [p0, p1, ...].
  • Keeping the copies at pos[l..r] means deleting everything between them: (pos[r] - pos[l] + 1) - (r - l + 1) deletions.
  • Slide a window over pos: shrink the left while deletions exceed k; the answer is the largest r - l + 1.

All the position lists together have length n, so this is O(n).

My Attempts
#

VersionProblem
Attempt 1, WASlid over the original array, checking length - most frequent count > k, and returned longest window - k. But a window does not necessarily delete exactly k. For nums = [2], k = 2, the answer is 1; this returned 1 - 2 = -1
Attempts 2–3, TLEReturned max(freq.values()) instead, which is correct, but took max over the whole count table every step: O(n · distinct values)
ACSlid separately over each value’s position list

Solution
#

class Solution:
    def longestEqualSubarray(self, nums: List[int], k: int) -> int:
        positions = defaultdict(list)
        for i, v in enumerate(nums):
            positions[v].append(i)

        best = 0
        for pos in positions.values():
            left = 0
            for right in range(len(pos)):
                while (pos[right] - pos[left] + 1) - (right - left + 1) > k:
                    left += 1                      # too many deletions in between
                best = max(best, right - left + 1)
        return best

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Using window length - k as the answer: the window does not necessarily delete exactly k.
  • Taking max over the count table every step: O(n · distinct).

Interview Explanation
#

What remains is one value, so I handle each value separately: list its positions, and keeping a consecutive run of them requires deleting the span of positions minus the count. A sliding window over the position list shrinks when deletions exceed k, and the number of copies in the window is a candidate answer. All lists total n, so time is O(n).

Related

LeetCode 2779: Maximum Beauty of an Array After Applying Operation
·2 mins
LeetCode Medium Sliding-Window Sorting Binary-Search Array
LeetCode 2779 note: each number can become anything in [x - k, x + k], so a group can become one value ⇔ max - min <= 2k; sort and find the longest such window
LeetCode 3795: Minimum Subarray Length With Distinct Sum At Least K
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 3795 note: a shortest-window slide where each value counts once; track each value’s last position, and subtract the left value only if it was the last occurrence
LeetCode 3679: Minimum Discards to Balance Inventory
·3 mins
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 note: the rule already decides what must be discarded, so simulate it; the length-w window counts only kept arrivals, and discarded ones must not be subtracted when they leave
LeetCode 2841: Maximum Sum of Almost Unique Subarray
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2841 note: a fixed window of length k keeps a sum and a count map; the number of distinct values is the map’s size, so delete keys that drop to zero
LeetCode 1248: Count Number of Nice Subarrays
·3 mins
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 1248 note: “exactly k odd numbers” is not monotonic, so compute “at most k” minus “at most k - 1”; or use prefix sums with a hash map
LeetCode 1838: Frequency of the Most Frequent Element
·2 mins
LeetCode Medium Sliding-Window Sorting Greedy Prefix-Sum Binary-Search Array
LeetCode 1838 note: after sorting, raising the whole window to nums[right] costs nums[right] × length − window sum; shrink the left while that exceeds k