Algorithm patterns← All patterns

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.

time O(n)space O(k) for the window's contents

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.

Example 1

Input: s = "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

Example 2

Input: s = "bbbbb"

Output: 1

Explanation: The answer is "b", with the length of 1.

Example 3

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"

a
0
b
1
c
2
a
3
b
4
c
5
b
6
b
7

seen (in window)

empty
best = 0

Empty window, empty set, best = 0.

1 / 25
solution.ts
1function lengthOfLongestSubstring(s: string): number {
2 const seen = new Set<string>();
3 let left = 0, best = 0;
4 for (let right = 0; right < s.length; right++) {
5 while (seen.has(s[right])) {
6 seen.delete(s[left]);
7 left++;
8 }
9 seen.add(s[right]);
10 best = Math.max(best, right - left + 1);
11 }
12 return best;
13}

Practice next