AlgoInsight

DSA problem

Longest Substring Without Repeating Characters

MediumSliding Window - Dynamic SizePattern: Variable-Size Sliding Windowtop75FreeAmazonGoogleMicrosoftBloombergAdobe

Given a string s, find the length of the longest substring that contains no repeating characters. A substring is a contiguous sequence of characters within the string, so the answer must be measured over a continuous run rather than an arbitrary selection of characters.

This is the canonical introduction to the variable-size sliding window. A brute-force approach would examine every possible substring and check each one for duplicates, which costs O(n^2) substrings times O(n) validation, an unacceptable O(n^3) overall. We need a way to extend and shrink a candidate window in amortized linear time.

The key observation is that the set of characters inside a valid window is always unique. As we push the right boundary forward to absorb a new character, the window may become invalid because that character already exists inside it. When that happens we advance the left boundary just far enough to evict the earlier copy, restoring the no-repeat invariant.

The intuition for the sliding window here is that the left pointer never moves backward. Every character is added once when the right pointer passes it and removed at most once when the left pointer passes it, so the total work is O(n). We track the best window length encountered while maintaining a hash set (or last-seen index map) of the characters currently inside the window.

Examples

Example 1
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with a length of 3. When the window reaches the second "a", the left pointer slides past the first "a" to remove the duplicate.
Example 2
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with a length of 1, since every character is identical and no window longer than one character can avoid repeats.
Example 3
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with a length of 3. Note that "pwke" is a subsequence, not a substring, so it does not count.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

sliding-windowhash-mapstringtwo-pointers

Browse all DSA problems