Video in progress

Strong Middle 🧠 Problem solving

How do you find the length of the longest substring that contains at most K distinct characters?

Sliding window: I advance the right edge, keep character counts in a Map, and shrink from the left whenever the number of distinct characters exceeds K. Each character enters the window once and leaves once, so it's O(n).

📖 Answer

Brute force, checking every substring, is O(n²) or O(n³). Here the window has a monotonic property: when the window grows, the number of distinct characters never decreases. That's why two pointers are enough.

static int longestWithKDistinct(String s, int k) {
    if (k == 0) return 0;
    Map<Character, Integer> freq = new HashMap<>();
    int left = 0, best = 0;
    for (int right = 0; right < s.length(); right++) {
        freq.merge(s.charAt(right), 1, Integer::sum);
        while (freq.size() > k) {               // condition broken — shrink from the left
            char c = s.charAt(left++);
            if (freq.merge(c, -1, Integer::sum) == 0) freq.remove(c);
        }
        best = Math.max(best, right - left + 1);
    }
    return best;
}

There is a while inside, but it's still O(n): left moves at most n times over the whole run. Say this amortization out loud in the interview; most people wrongly say "nested loop, so O(n²)".

A small optimization: if the alphabet is known (say ASCII only), use an int[128] and a separate distinct counter instead of the Map. The boxing goes away and it gets noticeably faster.

You must remove a key that drops to zero, otherwise freq.size() is wrong. This is the most common bug.