InterviewPrepKit

Home / Coding / Sliding Window

Longest Substring Without Repeating Characters

medium Original ↗
Solving tips
  • Classic longest-valid-window: 'all characters distinct' is monotone under shrinking, so grow right and only advance left forward.
  • Maintain a set of window chars; when the incoming char is already present, evict from the left until its duplicate is gone, then record the size.
  • Faster variant: a last-index dict lets you jump left to last[ch]+1 instead of crawling one char at a time.
  • Target O(n) time and O(min(n, alphabet)) space; pitfall in the jump version is guarding last[ch] >= left so a stale index never drags left backward (e.g. 'abba').

Problem

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

Substring means consecutive characters — "ace" inside "abcde" doesn’t count (that’s a subsequence). The answer is a length only; you don’t need to return the substring itself.

Examples

  • s = "abcabcbb"3"abc" is the longest stretch with all-distinct characters; the fourth character a repeats.
  • s = "bbbbb"1 — every window longer than one character contains a repeat.
  • s = "pwwkew"3"wke" (or "kew") works; "pwke" is not contiguous in a duplicate-free way because of the double w.

Constraints

  • 0 <= len(s) <= 5 * 10^4
  • s consists of English letters, digits, symbols, and spaces (general ASCII — don’t assume 26 letters).

O(n²) window checking is around 2.5 * 10^9 character comparisons in the worst case; the expected solution is a single O(n) pass.

Think about it first

Hint 1 If s[i..j] has all-distinct characters, so does every substring inside it. And if s[i..j] has a duplicate, so does every substring containing it. What does that monotone structure buy you?
Hint 2 Grow a window to the right, maintaining the set of characters inside it. When the incoming character is already in the set, which side must give ground, and how far?
Hint 3 Advance left, removing characters from the set, until the duplicate of the incoming character has been evicted. Faster variant: remember each character's last index in a dict and jump left directly to last_index + 1 (never backward).
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.