ProgrammingHardTCS NQT · Wipro pattern

What is printed?

What is printed?
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('pwwkew'), longest(''))
  1. A. 3 3 0
  2. B. 2 3 0
  3. C. 2 4 0
  4. D. 2 3 1

Correct answer: B. 2 3 0

In abba the longest repeat-free window is 2 characters, and in pwwkew it is wke with 3. The left edge moves only when the repeated character is still inside the window, and the empty string gives 0.

More Python Programming questions

Exams that ask this topic