ProgrammingHardTCS NQT · Accenture

The string "abcabcbb" is scanned with a sliding window that keeps the longest stretch without a repeated character. The procedure below returns that length. What is printed?

The string "abcabcbb" is scanned with a sliding window that keeps the longest stretch without a repeated character. The procedure below returns that length. What is printed?
left = 0; best = 0; last = empty map
for right = 0 to n - 1
    if s[right] was seen at index >= left then left = that index + 1
    last[s[right]] = right
    best = max(best, right - left + 1)
end for
Print best
  1. A. 3
  2. B. 2
  3. C. 8
  4. D. 0

Correct answer: A. 3

The longest window without repeats is abc, of length 3. Subtracting one from the best gives 2, printing the string length 8 is unrelated, and never updating best gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic