Sliding Window · Medium
Longest Substring Without Repeating Characters
Solve it on DeVert Campus - free code runner
Problem
You are given a string s. Find the length of the longest substring of s that does not contain any repeated character.
Input and output
Input: A single line containing the string s.
Output: Print a single integer: the length of the longest substring of s with all distinct characters.
Example
Input: abcabcbb Output: 3
Constraints
1 <= |s| <= 10^5
s consists of printable ASCII characters (no line breaks).
Key observation
This is arguably THE canonical variable-size sliding window problem - its 'expand right, jump/shrink left on violation' shape is the template for nearly every other variable-size window problem in this category.
Intuition
Find the length of the longest stretch of a string with no character repeated.
Brute force: Check every possible substring directly, verifying no character repeats within it - this costs O(n²) or worse, too slow for large strings.
Optimised: Recording the LAST SEEN INDEX of every character lets the window's left boundary JUMP DIRECTLY past a repeat the moment one is detected (rather than shrinking one position at a time), and since both left and right only ever move FORWARD across the whole scan, the total work stays O(n) despite handling repeats efficiently.
Step by step
1. Maintain a window [left, right] and a record of the LAST INDEX at which each character was seen.
2. When extending the window to include s[right], if that character was last seen AT OR AFTER left, move left to JUST PAST that previous occurrence (this is what removes the repeat from the window).
3. The answer is the maximum window length (right - left + 1) observed while scanning.
Complexity
Time: O(n) - both window boundaries move forward monotonically across the whole string.
Space: O(min(n, alphabet size)), for the last-seen-index map.
Edge cases
Handle a string where every character is identical (answer is 1) and a string where every character is already distinct (answer is |s|). A single-character string must also work (answer is 1).
Interview tip
Be ready to explain the 'jump left directly past the repeat' optimization versus a slower version that shrinks the window one character at a time - both are O(n) amortized, but the direct jump is a cleaner, more elegant implementation.