Given a string s, find the length of the longest substring without repeating characters.
s = "abcabcbb"3s = "pwwkew"3Set, l = 0, maxLen = 0r from 0 to n−1: expand window rightset.contains(s[r]): remove s[l], l++ (shrink left)s[r] to set; maxLen = max(maxLen, r − l + 1)maxLen after scanning all positionsA variable sliding window always holds a valid substring (no repeats). When s[r] duplicates a char already in the window, we shrink from the left until the duplicate is gone — the smallest valid window ending at r.
The HashSet gives O(1) membership checks. Each index enters and leaves the window at most once, so total work is O(n) despite the inner while loop.
maxLen tracks the best window seen so far. After each valid expansion at r, window length r − l + 1 is a candidate answer.
Checking every substring is O(n) cubed. Even a smarter check is still O(n²). That is too slow for long strings.
Keep a sliding window, from left to right. Right moves forward one character at a time. A hash map remembers the last index of every character. If the new character already appears inside the window, jump left to just after its previous index. At each step, update the best with the window length.
A window plus a last-seen map lets left jump, never step back. Only jump when the repeat is inside the current window.
Run the animation above on your own input, or watch the 1:51 video explanation of Longest Substring Without Repeating Characters with a dry run and Java code.