Longest Substring Without Repeating Characters
mediumBlind 75NeetCode 150stringssliding-windowhashing
Problem
Given a string, find the length of the longest contiguous substring that contains no repeated character.
Examples
Input: s = "abcabcbb"
Output: 3
The substring "abc" has length three.
Input: s = "bbbbb"
Output: 1
Only a single character can be in the window.
Constraints
- • 0 <= s.length <= 5 * 10^4
- • String contains printable ASCII characters
Hints(tap to reveal)
- 1. Grow a window and shrink it when a repeat appears.
- 2. Remember the last index of each character.
Optimal approach(spoiler)
- Maintain a sliding window with a left and right boundary.
- Store the most recent index of each character.
- When the current character was seen inside the window, jump the left boundary past it.
- Update the best window length at each step.
- O(n) time, O(min(n, alphabet)) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor