Skip to content

992. Subarrays with K Different Integers 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int subarraysWithKDistinct(vector<int>& nums, int k) {
    return subarrayWithAtMostKDistinct(nums, k) -
           subarrayWithAtMostKDistinct(nums, k - 1);
  }

 private:
  int subarrayWithAtMostKDistinct(const vector<int>& nums, int k) {
    int res = 0;
    vector<int> count(nums.size() + 1);

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      if (++count[nums[r]] == 1)
        --k;
      while (k == -1)
        if (--count[nums[l++]] == 0)
          ++k;
      res += r - l + 1;  // nums[l..r], nums[l + 1..r], ..., nums[r]
    }

    return res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int subarraysWithKDistinct(int[] nums, int k) {
    return subarraysWithAtMostKDistinct(nums, k) - subarraysWithAtMostKDistinct(nums, k - 1);
  }

  private int subarraysWithAtMostKDistinct(int[] nums, int k) {
    int res = 0;
    int[] count = new int[nums.length + 1];

    for (int l = 0, r = 0; r < nums.length; ++r) {
      if (++count[nums[r]] == 1)
        --k;
      while (k == -1)
        if (--count[nums[l++]] == 0)
          ++k;
      res += r - l + 1; // nums[l..r], nums[l + 1..r], ..., nums[r]
    }

    return res;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
    def subarraysWithAtMostKDistinct(k: int) -> int:
      res = 0
      count = collections.Counter()

      l = 0
      for r, num in enumerate(nums):
        count[num] += 1
        if count[num] == 1:
          k -= 1
        while k < 0:
          count[nums[l]] -= 1
          if count[nums[l]] == 0:
            k += 1
          l += 1
        res += r - l + 1  # nums[l..r], nums[l + 1..r], ..., nums[r]

      return res

    return subarraysWithAtMostKDistinct(k) - subarraysWithAtMostKDistinct(k - 1)