Data Structures & AlgorithmsVery hardProduct Company SDE · sliding window OA

Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the sliding-window code.

Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the sliding-window code.
s = 'aabcbcdbca'
need = len(set(s))
cnt = {}
l = 0
best = float('inf')
for r, ch in enumerate(s):
    cnt[ch] = cnt.get(ch, 0) + 1
    while len(cnt) == need:
        best = min(best, r - l + 1)
        cnt[s[l]] -= 1
        if cnt[s[l]] == 0:
            del cnt[s[l]]
        l += 1
print(best)
What is printed?
  1. A. 4
  2. B. 5
  3. C. 6
  4. D. 7

Correct answer: A. 4

The string has 4 distinct letters (a, b, c, d), and the shortest window with all of them is 'dbca' of length 4.

More Coding Interview Problems questions

Exams that ask this topic