Problem Description
Given a 0-indexed integer array nums and an integer k, you are allowed to delete at most k elements from the array. After deletion, you need to form a contiguous subarray where all its elements are equal. Your task is to determine the length of the longest possible equal subarray that can be obtained after making at most k deletions. Note that the empty subarray is also considered equal.
Key Insights
- The final equal subarray will consist of repeated instances of one particular number.
- For a fixed number, if you know all its indices, you can try to “connect” a group of these indices into one contiguous block by removing the elements in between.
- The required deletions for a block that spans positions i to j in the original array is (nums[j] - nums[i] + 1 - (number of occurrences within that block)).
- For each unique number, maintain a list of the indices where it occurs, then use a sliding window on these indices to determine the maximum block that can be “glued together” with at most k deletions.
- The overall answer is the maximum such block length among all unique numbers.
Space and Time Complexity
Time Complexity: O(n) overall, since each element is processed and every list of indices is slid over once. Space Complexity: O(n), for storing indices for each unique number.
Solution
We use a two-step approach:
- For each unique number in nums, record the positions at which it occurs.
- For each list of positions, apply a sliding window. For a window covering positions[i] to positions[j], the number of deletions required to “connect” these indices into a contiguous block is: (positions[j] - positions[i] + 1) - (j - i + 1) If this is <= k, then the window is valid.
- Track the maximum window size (i.e. the count of occurrences of a given number that can be joined after deletions) across all numbers.
This method leverages a hash table (or dictionary) to group indices and a sliding window (two pointers technique) to check the deletion constraint.