HardNo. 0992

Subarrays with K Different Integers — LeetCode 992 Python Solution

Topics
Array, Hash Table, Counting, Sliding Window
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0594Longest Harmonious SubsequenceEasy
0169Majority ElementEasy
0219Contains Duplicate IIEasy
0229Majority Element IIMedium
0347Top K Frequent ElementsMedium
0480Sliding Window MedianHard

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.

Free to download. Check it runs on your machine, then pick a plan.