LeetCode
Longest Substring Without Repeating Characters
MediumSliding Window & StringsDay 2
Problem Statement
Given a string s, find the length of the longest substring without repeating characters.
Examples (Test Cases & Output)
Example 1:
Input:
s = "abcabcbb"Output:
3Explanation: The answer is "abc", with the length of 3.
Example 2:
Input:
s = "bbbbb"Output:
1Explanation: The answer is "b", with the length of 1.
Example 3:
Input:
s = "pwwkew"Output:
3Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints
- 0 <= s.length <= 5 * 10^4
- s consists of English letters, digits, symbols and spaces.
Target Complexities
Optimal TimeO(N)
Optimal SpaceO(min(N, M))
Core Algorithmic Insight:
Using Math.max(left, map.get(char) + 1) prevents moving left backwards when the old duplicate is already outside our current window!
Font:Hack
Active Mode:Optimal Solution
Time: O(N)•Space: O(min(N, M))
Loading VS Code Hack Editor...
How This Code Works:
Dynamic Sliding Window with Two Pointers (left, right) and a Hash Map storing the most recent index of each character. When a duplicate character is encountered, advance left pointer directly to max(left, lastSeenIndex + 1), avoiding redundant step-by-step increments.