Subarrays with K Different Integers — LeetCode 992 Python Solution
HardArrayHash TableCountingSliding Window
- Problem
- #992
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an integer array nums and an integer k, return the number of good subarrays of nums. A good array is an array where the number of different integers in that array is exactly k.
Example
- Input
- nums = [1,2,1,2,3], k = 2
- Output
- 7
- Explanation
- Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
Python solution
Python
class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
def f(k):
pos = [0] * len(nums)
cnt = Counter()
j = 0
for i, x in enumerate(nums):
cnt[x] += 1
while len(cnt) > k:
cnt[nums[j]] -= 1
if cnt[nums[j]] == 0:
cnt.pop(nums[j])
j += 1
pos[i] = j
return pos
return sum(a - b for a, b in zip(f(k - 1), f(k)))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 992. Subarrays with K Different Integers is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 992. Subarrays with K Different Integers?
- LeetCode 992. Subarrays with K Different Integers is rated Hard on LeetCode.
- What is the time complexity of LeetCode 992. Subarrays with K Different Integers?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 992. Subarrays with K Different Integers?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 992. Subarrays with K Different Integers cover?
- LeetCode 992. Subarrays with K Different Integers is tagged Array, Hash Table, Counting and Sliding Window on LeetCode.