Problem Description
Given an integer array nums and an integer k, we define a subarray as "good" if the frequency of each element in the subarray is at most k. The goal is to find the length of the longest good subarray.
Key Insights
- Utilize a sliding window approach, maintaining a window that represents a contiguous subarray.
- Use a hash table (or dictionary) to count the frequency of elements within the current window.
- Expand the window by moving the right pointer, and when any element's frequency exceeds k, shrink the window from the left until the condition is met.
- The maximum valid window size encountered during the process is the solution.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the nums array, as each element is processed at most twice. Space Complexity: O(m), where m is the number of distinct elements in the current window (in worst-case, m ≈ n).
Solution
The solution leverages the sliding window technique combined with a frequency hash table. Initialize two pointers (left and right) to represent the window boundaries. As the right pointer iterates over the array, add the element into the frequency counter. If the newly added element's frequency exceeds k, increment the left pointer to reduce the window size until all element frequencies are at most k. Simultaneously track the maximum window length. This approach ensures we explore all possible good subarrays with linear time complexity.