NeetCode 150 / Sliding Window
016Longest Substring Without Repeating Characters
MediumSliding WindowO(n)
Dry run
s = "abcabcbb"Step 1 of 9
a
0lb
1c
2a
3b
4c
5b
6b
7Start with an empty seen map and an empty window. No character has been read yet.
Pythontime O(n) · space O(min(n, 26))
1def lengthOfLongestSubstring(s):
2 last = {}
3 left = 0
4 best = 0
5 for right, ch in enumerate(s):
6 if ch in last and last[ch] >= left:
7 left = last[ch] + 1
8 last[ch] = right
9 best = max(best, right - left + 1)
10 return best
Variables
left0
right—
char—
best0
Problem
Given a string s, find the length of the longest substring without repeating characters.
Examples
Input: s = "abcabcbb"Output: 3
"abc" is the longest
Input: s = "bbbbb"Output: 1
Constraints
- 0 ≤ s.length ≤ 5 × 10⁴
- s consists of English letters, digits, symbols and spaces
Intuition
Grow a window [left, right] that never contains a duplicate. Move right one character at a time; if the new character was last seen at or after left, move left just past that old position. The window length is right − left + 1.
Brute force → Optimal
Brute force
Check every substring and test whether all of its characters are distinct.
Time O(n²)Space O(n)
Optimal
Sliding window with a last-seen index map. Each character enters and leaves the window once, so the work is linear.
Time O(n)Space O(min(n, 26))
Complexity
Time O(n)Space O(min(n, 26))
Edge cases
- Empty string: the longest substring has length 0.
- All identical characters, e.g. "bbbbb": the window can only ever hold one character, so the answer is 1.
Common mistakes
- Moving left past the previous occurrence even when that occurrence is already outside the window, which shrinks the window incorrectly.
- Re-scanning the whole window for duplicates instead of remembering the last index of each character.
জটিলতা
O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(1)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Best Time to Buy and Sell Stockপরের সমস্যাLongest Repeating Character Replacement →