InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Longest Substring Without Repeating Characters

medium Original ↗ 00:00

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. If s[i..j] has a duplicate, so does every substring containing it. That monotonic structure is what lets a single left-to-right pass work.
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 pointer must move, 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).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug