Longest Substring with At Most K Distinct Characters, explained

Longest Substring with At Most K Distinct Characters is solved with a variable-size sliding window. Grow the window one character at a time while counting how often each character appears in it; when more than k different characters are inside, shrink from the left until only k remain, and record the longest window seen. Each character enters and leaves the window once, so the scan is O(n) time with O(k) extra memory.

By Published 8 min read

Restating the task

You get a string and a whole number k. Look at substrings, meaning unbroken stretches of the string, and keep only those that contain k or fewer different characters. Repeats of the same character are fine; it is the number of different characters that is limited. Return the length of the longest such stretch. When k is 0 the answer is 0, and when k is at least the number of different characters in the whole string, the answer is the full length.

Examples prepared for this page
StringkAnswerOne longest stretch
cabbage24abba
cabbage35cabba
mississippi27ississi
tttt14tttt
hello55the whole string
abc00nothing qualifies
Examples prepared for this page. Scroll sideways on a small screen.

What it tests in an interview

This is the general form of a family of window questions: the condition "at most k distinct" stays true when you remove characters from the left, so a window that only moves forward is enough. Interviewers check that you maintain the count map correctly, especially deleting keys whose count reaches zero, and that you can justify linear time despite the inner loop. Strong candidates also mention how the answer changes if the input is a stream too large to keep.

  • k equals 2. A popular special case with an O(1)-memory trick; see the two-distinct version.
  • Count windows instead of finding the longest. Add the window length at each step to count substrings with at most k distinct characters; subtract the same count for k - 1 to get exactly k, as in Subarrays with K Different Integers.
  • Return the substring. Track the start of the best window and slice at the end.
  • Exactly k, longest. Only update the best when the map has exactly k keys.

Brute force

def longest_k_distinct_brute(text, k):
    best = 0
    for start in range(len(text)):
        kinds = set()
        for end in range(start, len(text)):
            kinds.add(text[end])
            if len(kinds) > k:
                break
            best = max(best, end - start + 1)
    return best
Every start, extend with a set: O(n²) time, O(k) space.

This is fine to say first and to use as a reference in tests. The waste is visible: when the window starting at start breaks, the next start rebuilds almost the same window from scratch.

The sliding window with counts

  1. Add the new characterMove the right edge forward and increase that character's count in the map.
  2. Shrink while too many kindsWhile the map has more than k keys, decrease the count of the leftmost character and move the left edge forward. Delete a key when its count hits zero, because the number of keys is your distinct count.
  3. Record the windowThe window now has at most k kinds. Compare its length with the best.
def longest_k_distinct(text, k):
    counts = {}
    lo = best = 0
    for hi, ch in enumerate(text):
        counts[ch] = counts.get(ch, 0) + 1
        while len(counts) > k:
            out = text[lo]
            counts[out] -= 1
            if counts[out] == 0:
                del counts[out]
            lo += 1
        best = max(best, hi - lo + 1)
    return best
Python: counts in a dict. O(n) time, O(k) extra space.
function longestKDistinct(text, k) {
  const counts = new Map();
  let lo = 0;
  let best = 0;
  for (let hi = 0; hi < text.length; hi++) {
    const ch = text[hi];
    counts.set(ch, (counts.get(ch) || 0) + 1);
    while (counts.size > k) {
      const out = text[lo];
      const left = counts.get(out) - 1;
      if (left === 0) counts.delete(out);
      else counts.set(out, left);
      lo++;
    }
    best = Math.max(best, hi - lo + 1);
  }
  return best;
}
JavaScript: the same window with a Map.

With k = 0 the shrink loop empties the window after every character, so the best stays 0 with no special case. Still, many interviewers like to see an explicit early return; it costs one line and shows you thought about it.

Jumping the left edge with last positions

The count version may crawl the left edge across a long run of one character. A different bookkeeping removes that crawl: keep, for each character in the window, the index of its latest appearance, in a map that remembers insertion order. When a character arrives, delete and re-insert it so it moves to the newest end. When a (k+1)th kind arrives, the oldest entry in the map is the character whose latest appearance is furthest left; the window must start just after that index. Python's OrderedDict and JavaScript's Map both keep insertion order, so the oldest entry is the first key.

from collections import OrderedDict

def longest_k_distinct_jump(text, k):
    if k == 0:
        return 0
    last = OrderedDict()  # char -> latest index, oldest first
    lo = best = 0
    for hi, ch in enumerate(text):
        if ch in last:
            del last[ch]
        last[ch] = hi
        if len(last) > k:
            _, idx = last.popitem(last=False)
            lo = idx + 1
        best = max(best, hi - lo + 1)
    return best
Python: insertion-ordered last positions, each step O(1). Handy when characters arrive as a stream.
function longestKDistinctJump(text, k) {
  if (k === 0) return 0;
  const last = new Map();
  let lo = 0;
  let best = 0;
  for (let hi = 0; hi < text.length; hi++) {
    const ch = text[hi];
    last.delete(ch);
    last.set(ch, hi);
    if (last.size > k) {
      const oldest = last.keys().next().value;
      lo = last.get(oldest) + 1;
      last.delete(oldest);
    }
    best = Math.max(best, hi - lo + 1);
  }
  return best;
}
JavaScript: Map keeps insertion order, so the first key is the oldest.

Why is evicting the oldest entry right? Every character in the window other than the evicted one appears at or after the evicted index plus one, so starting there keeps them all and drops exactly one kind. Starting any earlier would keep the evicted kind as well, which would be k + 1.

Time and space

n is the string length
ApproachTimeExtra space
Every start, extend with a setO(n²)O(k)
Window with a count mapO(n), each character added and removed onceO(k)
Window with ordered last positionsO(n), O(1) per characterO(k)
n is the string length. Scroll sideways on a small screen.

Cases worth testing

  • k = 0, and the empty string.
  • k larger than the number of kinds in the string: the answer is the full length.
  • One repeated character, such as tttt.
  • Long runs that force the count version to crawl, such as aaaaaab with k = 1.
  • A best window at the very end of the string, which must be recorded after the last step.
  • Uppercase and lowercase versions of a letter, which are different characters unless told otherwise.

Errors to watch for

  • Leaving zero-count keys in the map, so its size overstates the number of kinds.
  • Using if instead of while when shrinking in the count version.
  • Recording the best length before the shrink, which counts an invalid window.
  • In the jump version, forgetting to delete and re-insert a repeat, so the map's order no longer reflects latest positions.
  • Claiming O(nk) because of the map; map operations are O(1) on average.

Explaining it in the room

Fictional example

A short narration that covers the key points
Candidate
If a stretch has at most k kinds, so does any part of it. So once the window gets too many kinds, I only need to move the left edge forward, never restart.
Candidate
I count characters in a map. When the map has more than k keys, I decrement from the left and delete keys at zero. The window length after that is a candidate.
Candidate
Both edges move forward at most n times, so it is linear, with at most k plus one keys in the map. If you want O(1) work per character, I can keep latest positions in an ordered map and jump the left edge instead.

Longest Substring with At Most Two Distinct Characters fixes k at 2 and can be done with three variables. Subarrays with K Different Integers turns this window into a counting tool for exactly k. The no-repeats version, where every character in the window must be different, is Longest Substring Without Repeating Characters.

Where Natively helps in practice

Natively runs on Mac and Windows, and during practice it can read a window problem like this from a screenshot and suggest code, including the variant you did not write, so you can compare a count map with the jump version side by side. Its transcript of your mock interview shows whether you said why the inner loop is still linear. Details on using an AI interview assistant for practice.

Questions people ask

How do you find the longest substring with at most k distinct characters?

Use a sliding window with a count map. Add each character on the right; while the map has more than k keys, remove characters from the left. Track the longest window.

What is the time complexity?

O(n), because each character enters and leaves the window at most once, with O(k) extra space for the map.

What happens when k is 0?

No non-empty substring qualifies, so the answer is 0. The window handles it, but an explicit early return is clearer.

Can the left edge jump instead of moving one step at a time?

Yes. Keep each character's latest index in an insertion-ordered map; when a (k+1)th kind arrives, evict the oldest entry and start just after its index.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP