Algorithm-Day08-Longest-Substring-Without-Repeating-Characters-lc-3
π§© Problem Description
Given a string s
, find the length of the longest substring without repeating characters.
Example:
1 | Input: s = "abcabcbb" |
π‘ Brute Force (Too Slow)
Try all substrings and check if characters are unique.
- Time: O(nΒ³)
- Space: O(k) for checking duplicates
β Correct but β inefficient.
π‘ Optimized Approach: Sliding Window + HashMap
We use a sliding window with two pointers:
- Expand
right
to include new characters - If a duplicate is found, move
left
to skip past the previous occurrence - Use a HashMap to store the last index of each character
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n)
Each character is visited at most twice. - Space Complexity: O(k)
Where k is the number of unique characters (e.g. 26 for lowercase letters, 128 for ASCII)
βοΈ Summary
- Sliding window is ideal for βlongest substringβ problems.
- Key trick: update
left
pointer only when needed, and never move it backward. - Using a HashMap allows constant-time character index tracking.
This is one of the most popular sliding window problems β understanding this unlocks many similar challenges like
Longest Subarray with Sum β€ k
, orMinimum Window Substring
.