Hard dsa sliding-window

Subarrays with K Different Integers

The 30 second answer

The number of subarrays with exactly k distinct values is the number with at most k distinct, minus the number with at most k minus one. 'At most k' is a standard variable window: I grow, shrink from the left when the distinct count exceeds the limit, and add the number of valid endings at the current right edge, which is the window length.

Could you say this in an interview?

Problem Given an integer array and an integer k, return how many contiguous subarrays contain exactly k different integers. Original: LeetCode 992: Subarrays with K Different Integers.

Understanding the prompt Exactly k is a harder constraint than at most k, because shrinking the window can jump from valid to invalid without a clean monotonic test. The standard trick is to subtract two 'at most' answers. A subarray is counted once for each ending index.

Pattern recognition Variable-size windows for an 'at most k distinct' condition, combined by subtraction to get 'exactly k'.

Brute force For every pair of ends, count distinct values in the range: O(n²).

Optimal atMost(k) walks a window with a frequency map. After each hi, while the map has more than k keys, decrement and maybe remove nums[lo] and advance lo. Every index from lo to hi is a valid start, so add hi - lo + 1. Return atMost(k) - atMost(k - 1). For k = 0 the helper returns 0.

Alternatives One pass that maintains two left edges, one for at most k and one for at most k − 1, is the same math with a single scan. The two-helper version is easier to explain.

Java solution

import java.util.HashMap;

public class SubarraysWithKDifferentIntegers {
    static int subarraysWithKDistinct(int[] nums, int k) {
        return atMost(nums, k) - atMost(nums, k - 1);
    }

    static int atMost(int[] nums, int k) {
        if (k <= 0) return 0;
        var count = new HashMap<Integer, Integer>();
        int lo = 0, ans = 0;
        for (int hi = 0; hi < nums.length; hi++) {
            count.merge(nums[hi], 1, Integer::sum);
            while (count.size() > k) {
                int x = nums[lo++];
                if (count.merge(x, -1, Integer::sum) == 0) count.remove(x);
            }
            ans += hi - lo + 1;
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(subarraysWithKDistinct(new int[] {1, 2, 1, 2, 3}, 2)); // 7
        System.out.println(subarraysWithKDistinct(new int[] {1, 2, 1, 3, 4}, 3)); // 3
    }
}

Complexity O(n) time, O(n) extra space in the worst case for the frequency map.

Edge cases

  • Official samples: [1,2,1,2,3] with k = 2 returns 7; [1,2,1,3,4] with k = 3 returns 3.
  • k = 1 counts the runs of equal values: each run of length L contributes L · (L + 1) / 2 subarrays.

Follow-ups

  • Fruit Into Baskets is the longest window with at most 2 distinct, not the count of windows.
  • Count subarrays with at most k distinct is the helper by itself.

Tests [1,2,1,2,3] with k=2 returns 7. [1,2,1,3,4] with k=3 returns 3.

How to say it in the interview "Exactly k distinct is atMost(k) minus atMost(k minus 1). For atMost I grow a window, shrink when I have too many distinct values, and at each right edge I add the window length, because every start inside the window is valid. Two linear passes."

Sources (2)
  1. LeetCode 992: Subarrays with K Different Integersleetcode.com
  2. Java SE 17 API: Map.mergedocs.oracle.com