Pattern this teaches:Sliding Window
Longest Substring Without Repeating Characters
A medium Strings interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Strings
- Sheets
- 3
- Core for
- 14 roles
The problem
Determine the length of the longest contiguous substring containing only unique characters from a given string.
Example 1
- Input
- s="abcabcbb"
- Output
- 3
- Why
- The longest non-repeating substring is "abc", which has length 3.
Example 2
- Input
- s="bbbbb"
- Output
- 1
- Why
- The longest valid substring is "b", having length 1.
Example 3
- Input
- s="pwwkew"
- Output
- 3
- Why
- The longest valid substring without duplicate symbols is "wke", with length 3.
Constraints
- 0 <= s.length <= 5 * 10^4
- s consists of English letters, digits, symbols and spaces
How to think about it
Updated 2026-09-29Instead of discarding the whole accumulated substring when a duplicate character arrives, only the prefix up to that duplicate's previous position becomes obsolete. Recording the most recent index seen for every symbol allows the left boundary to hop directly past that index, ensuring the active span between pointers always holds unique items without restarting from scratch.
Approaches, worst first
Enumerate all candidate substrings
time O(n^3) · space O(min(n, m))
Examine every pair of starting and ending indices, using a frequency set to check if any character repeats within that slice. Generating all substrings takes quadratic iterations, and scanning each candidate pushes the total runtime into cubic territory.
Sliding window with hash set
time O(n) · space O(min(n, m))
Expand the right pointer one symbol at a time while inserting elements into a set. Whenever the right symbol already exists in the set, incrementally delete characters from the left pointer until the collision disappears. Each character enters and leaves the set once.
Jump using last-seen indexWrite this one
time O(n) · space O(min(n, m))
Map each character to its most recently observed index. On encountering an already seen character at index right, raise the left pointer directly to max(left, last_seen[char] + 1). The window size right - left + 1 competes for the record length on each iteration in a single pass.
Where people lose marks · 3
- Jumping the left pointer backward when a duplicate was observed before the current left boundary; must take max(left, last_seen[char] + 1) rather than overwriting left directly.
- An empty string input: length is 0, so the maximum length accumulator must initialize to 0.
- Assuming characters are only lowercase ASCII letters; inputs can include spaces, digits, and symbols, breaking fixed 26-element array lookups unless sized for 128 or 256 entries.
Full solution
Jump using last-seen index: track each character's most recent position and snap the left boundary past it on a collision, giving a single O(n) pass instead of the sliding-window set's incremental left-side deletions.
Python
def length_of_longest_substring(s: str) -> int:
last_seen: dict[str, int] = {}
left = 0
best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1
last_seen[ch] = right
best = max(best, right - left + 1)
return best
JavaScript
function lengthOfLongestSubstring(s) {
const lastSeen = new Map();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
if (lastSeen.has(ch) && lastSeen.get(ch) >= left) {
left = lastSeen.get(ch) + 1;
}
lastSeen.set(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}
The theory behind it
Strings — the ground this problem stands on. All Strings problems
What Strings is
A string is an ordered necklace of text characters, like letters printed along a ribbon of paper. Each character sits at an exact numeric slot, holding a glyph such as a letter, punctuation mark, or digit. In many programming languages, ribbons cannot be edited after creation, meaning changing a single character requires pressing an entirely new ribbon from scratch.
When to reach for it
Reach for string techniques when inputs consist of words, DNA sequences, serialized data formats, or sentences. Clues include questions testing palindromes, anagram matches, substring patterns, parenthesis balancing, or character frequency counts. Whenever an algorithm asks to transform capitalization, parse structured tokens, or compute edits between two phrases, string representations are the core subject.
How the pattern works
Think of characters as small integer codes ranging across standard character sets. Frequency tables with fixed sizes often replace heavy hash maps when tallying occurrences. For search tasks, maintain rolling state using character indices or sliding borders. When building output text through repeated appends, accumulate pieces inside a mutable list or string builder rather than concatenating strings directly, avoiding quadratic copy overhead.
More Strings problems
Target Roles
Core requirement for 14 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .