lc.algoro.dev
← Back to problems

Longest Substring Without Repeating Characters

Medium #3 View Problem ↗ Hash Table • String • Sliding Window

Intuition

We’re looking for the longest window of characters with no repeats.

Expand the window to the right; if we see a duplicate, jump the left edge just past the previous occurrence so the window remains duplicate-free.


Approach


Proof of Correctness

Invariant: The current window s[left..right] contains no duplicates.


Complexity


Code

TypeScript Solution
export function lengthOfLongestSubstring(s: string): number {
  const last = new Map<string, number>();
  let best = 0;
  let left = 0;

  for (let right = 0; right < s.length; right++) {
    const ch = s[right];

    if (last.has(ch) && (last.get(ch) as number) >= left) {
      left = (last.get(ch) as number) + 1;
    }

    last.set(ch, right);
    best = Math.max(best, right - left + 1);
  }

  return best;
}
Python Solution
def lengthOfLongestSubstring(s: str) -> int:
    last = {}
    best = 0
    left = 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