Link: 3. Longest Substring Without Repeating Characters
Track: NeetCode150
Question
Restate the problem
- Given a String
s - Find the length of the longest substring without repeating characters
- Return
int
Edge Case
- if not
s, return 0
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Sliding window |
Method 1: Sliding window
Key idea: Maintain a window
[left, right]that is always valid (no character count > 1); expandright, and when a duplicate appears, shrink fromleftuntil valid again.
Approach
- Expand the window by moving
rightand addings[right] - While the window is invalid (a duplicate exists),
- Shrink by moving
leftand removings[left]
- Shrink by moving
- Update the max length after the window becomes valid
Complexity
- Time Complexity:
- Space Complexity:
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic = {}
left = right = 0
length = 0
while right < len(s):
dic[s[right]] = dic.get(s[right], 0) + 1
while dic[s[right]] > 1:
dic[s[left]] -= 1
left += 1
length = max(length, right - left + 1)
right += 1
return lengthCommon Mistake
- Must use
while dic[s[right]] > 1because you may need to moveleftmultiple steps to remove the duplicate.