Pattern 02 / 10 · Fundamentals
Sliding Window
Grow the window to the right, shrink it from the left, never look back.
The idea
Keep a window [left, right] and a small summary of what is inside it (a set, a count, a sum). Move right one step at a time; whenever the window breaks the rule, move left until it is valid again. Each index enters and leaves the window once.
Reach for it when
- The question is about a contiguous subarray or substring.
- You want the longest, shortest or best window that satisfies a rule.
- A brute force would recheck overlapping ranges again and again.
Watch it run
3. Longest Substring Without Repeating Characters
Find the length of the longest substring that has no repeated characters.
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. "pwke" is a subsequence, not a substring.
WALKTHROUGH INPUT · s = "abcabcbb"
seen (in window)
Empty window, empty set, best = 0.
1function lengthOfLongestSubstring(s: string): number {2const seen = new Set<string>();3let left = 0, best = 0;4for (let right = 0; right < s.length; right++) {5while (seen.has(s[right])) {6seen.delete(s[left]);7left++;8}9seen.add(s[right]);10best = Math.max(best, right - left + 1);11}12return best;13}