Find a longest substring with a sliding window
Keep a left boundary and the most recent position of each character. When a character repeats inside the current window, move the left boundary past its previous position. Never move it backwards. Each character is visited once: expected O(n) time and O(u) space for u distinct characters. Sum-based windows need additional assumptions: negative values can break the usual expand-and-shrink rule.
def longest_unique(text):
last = {}
left = best = 0
for right, char in enumerate(text):
left = max(left, last.get(char, -1) + 1)
last[char] = right
best = max(best, right - left + 1)
return best
assert longest_unique("abba") == 2
assert longest_unique("") == 0These examples use Python 3 and include assertions you can run locally.
Try an original practice problem