Skip to content
DSA in JavaScript
← All patterns

Sliding Window

0/18 solved

What it is

Keep a window over a contiguous part of the array. Slide it right by adding one item and dropping one, updating the answer as you go instead of recomputing.

Used for

Longest or shortest subarray or substring with a condition, fixed-size window maximums.
L, R

Window "a", length 1

best so far: 1

Step 1 of 6

Goal: find the longest stretch of letters with no letter repeated. Checking every stretch is slow. Instead keep one window over the string and only ever slide it forward.

You see

  • Longest or shortest contiguous subarray or substring
  • Constraint on the window (at most k distinct, sum >= s)
  • Fixed size k window

Learn it in

ArraysStringsHash TableDeque (Double-Ended Queue)

Template

function longestUnique(s) {  const seen = new Map();  let best = 0, left = 0;  for (let right = 0; right < s.length; right++) {    if (seen.get(s[right]) >= left) left = seen.get(s[right]) + 1;    seen.set(s[right], right);    best = Math.max(best, right - left + 1);  }  return best;}

Practice problems