Magicsheet logo

Find the Longest Equal Subarray

Medium
94.5%
Updated 6/1/2025

Find the Longest Equal Subarray

What is this problem about?

In the Find the Longest Equal Subarray coding problem, you are given an array of integers and an integer kk. You want to find the longest possible subarray where all elements are the same, but you are allowed to delete up to kk elements from the original array to achieve this. You want to return the length of this "equal" subarray (the count of the identical elements).

Why is this asked in interviews?

Google and Palo Alto Networks use this problem to test your mastery of the Sliding Window interview pattern. It evaluation whether you can efficiently find the most frequent element in a window and determine if the "other" elements (the ones that would need to be deleted) exceed kk. It’s a sophisticated variation of the "Longest Repeating Character Replacement" problem.

Algorithmic pattern used

This is a Sliding Window problem combined with a Hash Table.

  1. For each unique number in the array, you could potentially form a window. However, a more efficient way is to maintain a single sliding window [left, right].
  2. Use a Hash Map to track the frequencies of all numbers within the current window.
  3. Maintain a variable maxFreq which is the frequency of the most common element in the current window.
  4. The number of elements to delete in the current window is (windowSize - maxFreq).
  5. If deletions >k> k, shrink the window from the left.
  6. The answer is the global maximum of maxFreq.

Example explanation

nums = [1, 3, 2, 3, 1, 3], k=3k = 3.

  1. Window [1, 3, 2, 3]: size 4. Freqs: {1:1, 3:2, 2:1}. maxFreq = 2.
  2. Deletions = 42=2k4 - 2 = 2 \le k.
  3. Expand: [1, 3, 2, 3, 1, 3]: size 6. Freqs: {1:2, 3:3, 2:1}. maxFreq = 3.
  4. Deletions = 63=3k6 - 3 = 3 \le k.
  5. Max equal length found is 3 (using the number 3).

Common mistakes candidates make

  • Re-calculating maxFreq: Iterating through the map to find the max frequency every time the window moves, which makes the solution O(NimesextUniqueCount)O(N imes ext{UniqueCount}). maxFreq only needs to be updated when a new element enters the window.
  • Wrong return value: Returning the window size instead of the count of the identical elements.
  • Brute Force: Trying to solve for each number separately without realizing a single sliding window can track the "best" candidate.

Interview preparation tip

Master the "Longest Subarray with Constraint" pattern. The key is usually: WindowSize - BestElementCount <= K. This allows you to find the longest segment that can be "cleaned up" into a uniform state.

Similar Questions