Data Structures & AlgorithmsHardAmazon · Microsoft OA

Find the bug: the code below should return the length of the longest substring without repeating characters.

Find the bug: the code below should return the length of the longest substring without repeating characters.
def longest(s):
    last, left, best = {}, 0, 0
    for i, c in enumerate(s):
        if c in last:
            left = last[c] + 1
        last[c] = i
        best = max(best, i - left + 1)
    return best
print(longest("abba"))
What is printed?
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 1

Correct answer: A. 3

At the final 'a', last['a'] = 0, so left jumps BACK from 2 to 1 and the window 'bba' (length 3) is counted although it repeats b. The fix is left = max(left, last[c] + 1); the correct answer for 'abba' is 2.

More Coding Interview Problems questions

Exams that ask this topic