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 += 1Why can the window stay too large?- A. l should move before decrementing
- B. The loop should be an if
- 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
- 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
- Problem: Merge sort's merge step in Java uses if (a[i] < b[j]) take a[i]; else take b[j];. What property is lost compared with <=?
- Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print? python def twosumsorted(a, t)…
- Problem: A ride app must repeatedly add drivers with ratings and remove the highest-rated driver, n = 10⁵ operations. Which data structure…
- Problem: A leaderboard needs: insert a score, delete a score, and 'how many scores are below x?' – all online, 10⁵ operations, scores up…
- Problem: A browser keeps history so that 'back' and 'forward' work like the real buttons, and visiting a new page clears the forward…
- Problem: For a stream of n = 10⁶ (user, timestamp) hits, answer 'how many hits in the last 300 seconds?' after each new hit (timestamps…