#2831

Find the Longest Equal Subarray

Medium
ArrayHash TableBinary SearchSliding WindowHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a sliding window technique to efficiently find the longest subarray where we can delete up to k elements. This approach is faster because it avoids redundant checks and focuses on maintaining a valid window.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency map to count occurrences of each number.
  2. 2Step 2: For each unique number in the array, maintain a sliding window of indices where this number appears.
  3. 3Step 3: Expand the window until the number of deletions needed exceeds k, then shrink the window from the left to maintain the condition.
solution.py20 lines
1# Full working Python code
2
3def longestEqualSubarray(nums, k):
4    from collections import defaultdict
5    freq_map = defaultdict(list)
6    for i, num in enumerate(nums):
7        freq_map[num].append(i)
8    max_length = 0
9    for indices in freq_map.values():
10        left = 0
11        for right in range(len(indices)):
12            deletions = indices[right] - indices[left] - right + left
13            while deletions > k:
14                left += 1
15                deletions = indices[right] - indices[left] - right + left
16            max_length = max(max_length, right - left + 1)
17    return max_length
18
19# Example usage
20print(longestEqualSubarray([1,3,2,3,1,3], 3))

Complexity note: This complexity is due to the single pass through the array and maintaining a frequency map, making it much more efficient than the brute-force approach.

  • 1Using a frequency map allows us to focus on each unique number, reducing unnecessary checks.
  • 2The sliding window technique efficiently manages the range of indices while keeping track of deletions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.