Data Structures & AlgorithmsHardProduct Company SDE · sliding window OA

Problem: What is the length of the shortest substring of 'aabbcxa' that contains every letter of 'abc'? Run the sliding-window code.

Problem: What is the length of the shortest substring of 'aabbcxa' that contains every letter of 'abc'? Run the sliding-window code.
from collections import Counter
s, t = 'aabbcxa', 'abc'
need = Counter(t)
have = Counter()
missing = len(t)
l = 0
best = float('inf')
for r, ch in enumerate(s):
    if need[ch] and have[ch] < need[ch]:
        missing -= 1
    have[ch] += 1
    while missing == 0:
        best = min(best, r - l + 1)
        have[s[l]] -= 1
        if need[s[l]] and have[s[l]] < need[s[l]]:
            missing += 1
        l += 1
print(best)
What is printed?
  1. A. 3
  2. B. 5
  3. C. 6
  4. D. 4

Correct answer: D. 4

The window 'abbc' at indices 1 to 4 contains a, b and c and has length 4. No window of length 3 contains all three letters.

More Coding Interview Problems questions

Exams that ask this topic