Python coding

Longest run without repeats

Given a string s, return the length of the longest contiguous substring in which no character appears twice.

Aim for one pass over s.

Besides the tests, one large input (a 6,000-character string) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • longest_unique("abcabcbb") → 3
  • longest_unique("bbbbb") → 1
  • longest_unique("pwwkew") → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Keep a window [left, right] that never contains a repeat; move right one step at a time.

Hint 2

Remember the last index of each character; on a repeat inside the window, jump left past it.

Solution and why it works
pythonO(n) · O(k), k = distinct characters
def longest_unique(s: str) -> int:
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

Each index enters the window once and left only moves forward, so the scan is linear. Checking last[ch] >= left matters: an old occurrence outside the window ("abba") must not pull left backwards.

Related lab: Sliding window, step by step