Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the length of the longest substring of a log line with no repeated character.

Problem: Find the length of the longest substring of a log line with no repeated character.
def longest(s):
    last = {}
    l = best = 0
    for r, ch in enumerate(s):
        if ch in last and last[ch] >= l:
            l = last[ch] + 1
        last[ch] = r
        best = max(best, r - l + 1)
    return best
print(longest("abba"), longest("dvdf"))
What is printed?
  1. A. 2 2
  2. B. 3 3
  3. C. 1 3
  4. D. 2 3

Correct answer: D. 2 3

The window start jumps to just after the previous occurrence, but only if that occurrence is inside the window (last[ch] >= l). For "abba" the final 'a' was last seen at 0, outside the window [2..], so l stays 2 and the best is 2; "dvdf" gives "vdf" = 3. Dropping the last[ch] >= l check moves l backwards and gives a wrong length 3 for "abba". O(n).

More Coding Interview Problems questions

Exams that ask this topic