#3859

Count Subarrays With K Distinct Integers

Hard
ArrayHash TableSliding WindowCountingHash 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)

Use a sliding window to efficiently count subarrays with at most k distinct integers, then subtract those with at most k-1 distinct integers.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a helper function to count subarrays with at most k distinct integers, ensuring each appears at least m times.
  2. 2Step 2: Use the helper function to get counts for k and k-1.
  3. 3Step 3: Return the difference between the two counts.
solution.py14 lines
1def at_most(nums, k, m):
2    count, left, freq = 0, 0, {}
3    for right in range(len(nums)):
4        freq[nums[right]] = freq.get(nums[right], 0) + 1
5        while len(freq) > k or any(v < m for v in freq.values()):
6            freq[nums[left]] -= 1
7            if freq[nums[left]] == 0:
8                del freq[nums[left]]
9            left += 1
10        count += right - left + 1
11    return count
12
13def countSubarrays(nums, k, m):
14    return at_most(nums, k, m) - at_most(nums, k - 1, m)

Complexity note: Sliding window allows us to process each element in linear time, maintaining a frequency map.

  • 1Using a sliding window optimizes the search for valid subarrays.
  • 2Counting distinct integers efficiently is crucial for performance.

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