Longest Substring Without Repeating Characters
Given a string s
Example 1
Input: s = "abcabcbb"
Output: 3
Explanation: The longest substring without repeating characters is "abc", which has length 3.
Output: 3
Explanation: The longest substring without repeating characters is "abc", which has length 3.
Example 2
Input: s = "bbbbb"
Output: 1
Explanation: The longest substring is "b", with length 1.
Output: 1
Explanation: The longest substring is "b", with length 1.
Example 3
Input: s = "pwwkew"
Output: 3
Explanation: The longest substring is "wke", with length 3.
Output: 3
Explanation: The longest substring is "wke", with length 3.
Constraints:
0 <= s.length <= 5 * 104 consists of English letters, digits, symbols and spaces.s
Solution - Sliding Window with HashMap
This problem is a classic application of the sliding window technique. We maintain a window
defined by two pointers, leftrightHashMapleft
Implementation steps:
-
Use a
to store each character's most recent index in the string.HashMap<Character, Integer> -
Expand the window by advancing
one character at a time.right -
If the character at
is already in the map and its stored index is within the current window (right ), move>= left toleft to skip past the duplicate.map.get(c) + 1 - Update the map with the current index and track the maximum window size seen so far.
Java
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>(); // char -> last seen index
int maxLen = 0;
int left = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
// If c was seen before and is within the current window, shrink from left
if (map.containsKey(c) && map.get(c) >= left) {
left = map.get(c) + 1;
}
map.put(c, right); // update last seen index of c
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
Trace through Example 1: s = "abcabcbb"
| right | char | left | window | maxLen |
|---|---|---|---|---|
| 0 | a | 0 | "a" | 1 |
| 1 | b | 0 | "ab" | 2 |
| 2 | c | 0 | "abc" | 3 |
| 3 | a | 1 | "bca" | 3 |
| 4 | b | 2 | "cab" | 3 |
| 5 | c | 3 | "abc" | 3 |
| 6 | b | 5 | "cb" | 3 |
| 7 | b | 7 | "b" | 3 |
Complexity Analysis
-
Time complexity: O(n). Each character is visited at most twice (once by
, once byright ).left -
Space complexity: O(min(n, m)): where
is the size of the character set (e.g. 26 for lowercase letters, 128 for ASCII). The map stores at most one entry per unique character.m