Given a string
Output: 3
Explanation: The longest substring without repeating characters is "abc", which has length 3.
Output: 1
Explanation: The longest substring is "b", with length 1.
Output: 3
Explanation: The longest substring is "wke", with length 3.
Constraints:
0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces.
Contents
Solution - Sliding Window with HashMap Complexity Analysis
This problem is a classic application of the sliding window technique. We maintain a window
defined by two pointers,
Implementation steps:
-
Use a
HashMap<Character, Integer> to store each character's most recent index in the string. -
Expand the window by advancing
right one character at a time. -
If the character at
right is already in the map and its stored index is within the current window (>= left ), moveleft tomap.get(c) + 1 to skip past the duplicate. - Update the map with the current index and track the maximum window size seen so far.
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 |
-
Time complexity: O(n) — each character is visited at most twice (once by
right , once byleft ). -
Space complexity: O(min(n, m)) — where
m 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.