Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while len(map) > k:

Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while len(map) > k:
while len(freq) > k:
    freq[s[l]] -= 1
    l += 1
Why can the window stay too large?
  1. A. l should move before decrementing
  2. B. The loop should be an if
  3. C. Keys whose count reaches 0 are never deleted, so len(freq) never drops – it must del freq[s[l]] when the count hits 0
  4. D. freq must be an array of size 26

Correct answer: C. Keys whose count reaches 0 are never deleted, so len(freq) never drops – it must del freq[s[l]] when the count hits 0

len(freq) counts keys, including those with count 0. Without deleting them the loop keeps shrinking until the window is empty, or never reports correct sizes. 'if' instead of 'while' would shrink only one step, which is a different bug. Order of l += 1 is fine here.

More Coding Interview Problems questions

Exams that ask this topic