Longest Substring Without Repeating Characters – Solution & Complexity
Watch: Longest Substring Without Repeating Characters with a sliding window
Grow a window to the right one character at a time. When a character repeats, jump the left edge past its previous position, which a map of last-seen indices gives you in O(1). The answer is the widest window seen. O(n) time.
Solution Walkthrough
Step 1: Understand the Goal
- We need the length of the longest contiguous substring with no repeated characters.
- A substring must keep characters in their original order and be continuous.
- We only return the length, not the substring itself.
Step 2: Brute Force Idea
- Try every possible start index and extend until a duplicate appears.
- Track the best length seen.
- This works but can be O(n²) because many characters are scanned repeatedly.
Step 3: Use a Sliding Window
- Keep a window
[left, right]that always contains unique characters. - Move
rightforward one character at a time. - If a character repeats, move
leftjust past the previous occurrence. - This avoids rechecking characters that are already known to be valid.
- Keep a window
Step 4: Track Last Seen Positions
- Store the most recent index for each character in a dictionary.
- When
s[right]was last seen inside the current window, updateleft. - Use
maxsoleftnever moves backward.
Step 5: Final Solution and Complexity
- Each character is processed once by the right pointer.
- The left pointer only moves forward.
- Time complexity is O(n).
- Space complexity is O(k), where
kis the number of distinct characters stored.