Subarrays with K Different Integers — LeetCode 992 Python Solution

HardArrayHash TableCountingSliding Window
Problem
#992
Reading time
3 min

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

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview