#2537

Count the Number of Good Subarrays

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 a sliding window approach to efficiently count good subarrays without needing to check every possible subarray. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use two pointers (left and right) to represent the current subarray.
  2. 2Step 2: Maintain a frequency map to count occurrences of each number in the current subarray.
  3. 3Step 3: Expand the right pointer to include new elements until the number of pairs is at least k.
  4. 4Step 4: Move the left pointer to shrink the window while still maintaining at least k pairs, counting valid subarrays as you go.
solution.py14 lines
1def countGoodSubarrays(nums, k):
2    count = 0
3    left = 0
4    pairs_count = 0
5    freq = {}
6    for right in range(len(nums)):
7        freq[nums[right]] = freq.get(nums[right], 0) + 1
8        pairs_count += freq[nums[right]] - 1
9        while pairs_count >= k:
10            count += len(nums) - right
11            freq[nums[left]] -= 1
12            pairs_count -= freq[nums[left]]
13            left += 1
14    return count

Complexity note: This complexity is achieved because we only traverse the array once with two pointers, maintaining a frequency map.

  • 1Understanding how pairs are formed is crucial for counting efficiently.
  • 2Using a frequency map allows us to quickly determine how many pairs exist as we expand or contract our window.

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