Longest Substring Without Repeating Characters – Solution & Complexity
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.
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.
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.
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.
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.