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.