LeetCode solutions

1034. Subarrays with K Different Integers

My accepted C++ solution to LeetCode problem 1034, Subarrays with K Different Integers, running in 51ms.

  • Difficulty: Hard
  • C++
  • Runtime 51ms
  • Memory 53.4MB

Read the problem on LeetCode View on GitHub

C++

Accepted on LeetCode — runtime 51ms, memory 53.4MB, accepted 2025-12-27.

cpp
class Solution {
    public:
    int subarraysWithKDistinct(vector<int>& nums, int k) {
        return atMost(nums, k) - atMost(nums, k - 1);
    }

    int atMost(vector<int>& nums, int k) {
        if (k == 0) return 0;
        unordered_map<int, int> count;
        int left = 0, res = 0;

        for (int right = 0; right < nums.size(); right++) {
            if (count[nums[right]] == 0) k--;
            count[nums[right]]++;

            while (k < 0) {
                count[nums[left]]--;
                if (count[nums[left]] == 0) k++;
                left++;
            }
            res += right - left + 1;
        }
        return res;
    }
};

Source