#2958

Length of Longest Subarray With at Most K Frequency

Medium
ArrayHash TableSliding 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 the sliding window technique to efficiently find the longest good subarray in a single pass. This reduces the time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two pointers (left and right) to represent the current window of the subarray.
  2. 2Step 2: Use a hashmap to track the frequency of elements in the current window.
  3. 3Step 3: Expand the right pointer to include new elements and update their frequency.
  4. 4Step 4: If any frequency exceeds k, increment the left pointer to shrink the window until all frequencies are valid.
  5. 5Step 5: Update the maximum length of the good subarray during the process.
solution.py18 lines
1# Full working Python code
2
3def longest_good_subarray(nums, k):
4    left = 0
5    max_length = 0
6    freq = {}
7    for right in range(len(nums)):
8        freq[nums[right]] = freq.get(nums[right], 0) + 1
9        while freq[nums[right]] > k:
10            freq[nums[left]] -= 1
11            if freq[nums[left]] == 0:
12                del freq[nums[left]]
13            left += 1
14        max_length = max(max_length, right - left + 1)
15    return max_length
16
17# Example usage
18print(longest_good_subarray([1,2,3,1,2,3,1,2], 2))  # Output: 6

Complexity note: The time complexity is O(n) because we traverse the array with two pointers, each moving at most n times. The space complexity is O(n) due to the hashmap storing frequencies of elements.

  • 1Using a sliding window allows us to efficiently manage the current subarray without needing to recheck previous elements.
  • 2Hashmaps are useful for counting frequencies dynamically as we expand and contract our window.

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