Longest Substring Without Repeating Characters
Examples
Example 1:
Input: s = "zxyzxyz"
Output: 3
Explanation:
Example 2:
Input: s = "xxxx"
Output: 1
Example 1:
Input: s = "zxyzxyz"
Output: 3
Explanation:
Example 2:
Input: s = "xxxx"
Output: 1
Given a string s, find the length of the longest substring without duplicate characters.
A substring is a contiguous sequence of characters within a string.
The string "xyz" is the longest without duplicate characters.
0 <= s.length <= 1000s may consist of printable ASCII characters.Use a sliding window with a map of each character's most recent index. Expand the right pointer; when a duplicate is found inside the current window, move the left pointer to one past the last occurrence. Track the maximum window length seen. This handles empty strings and repeated characters efficiently.
The window [left, right] always contains unique characters. When a duplicate appears, moving left past its last position restores the invariant without discarding potential longer substrings. The maximum length over all valid windows is the answer.
O(n)O(min(n, alphabet))class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last_index = {}
left = 0
best = 0
for right, ch in enumerate(s):
if ch in last_index and last_index[ch] >= left:
left = last_index[ch] + 1
last_index[ch] = right
best = max(best, right - left + 1)
return best