← Back to DSA mapMedium
Sliding Window
Longest Substring Without Repeating Characters
Length of the longest substring with all-distinct characters.
Problem
Given a string s, return the length of the longest substring that contains no repeating characters.
- A substring is contiguous - "pwke" in "pwwkew" is a subsequence, not a substring.
- The empty string has length 0.
Examples
Input: s = "abcabcbb"
Output: 3
"abc"
Input: s = "bbbbb"
Output: 1
"b"
Input: s = "pwwkew"
Output: 3
"wke"
Approach
Time O(n)Space O(min(n, charset))
- Keep a stretch of the string from L to R that has no repeats, plus a map from each character to the last position you saw it.
- Move R forward one character at a time.
- If the character was last seen inside the window (lastSeen >= L), jump L to lastSeen + 1 so the window is valid again.
- Record its new position, then update best with the window length R - L + 1.
Brute force: Start at every position and extend, using a set, until a character repeats - a loop inside a loop.
Common mistakes
- Jumping L to lastSeen + 1 without checking lastSeen >= L can move L backwards to a stale position.
- Removing characters one by one from a set also works, but takes more steps than jumping L.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
SW
Solution · JS
Window · L=— R=—
a0
b1
c2
a3
b4
c5
b6
b7
MAP{ }
Left
—
Right
—
Win
0
Best
0
Step
—
0 / 0
1×
Execution log
steps appear here…
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
Edit and run it here
JavaScript solution
Loading...
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
All courses
24 courses in 5 subjects
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned
Frontend
Fundamentals
On this page
0 sections