Skip to the page

Linear patterns · mid

Sliding window in JavaScript

A sliding window keeps a range [left, right] and updates its state as right grows and left shrinks, so best-substring and best-subarray problems run in O(n). In JavaScript, keep the state in a Map or a 26-length array, and store indices instead of building substrings inside the loop.

The notes

What you must know

  • Fixed size k: add the new element, remove the one leaving (sum += a[i] − a[i − k]).
  • Variable size: expand right every step; while the window is invalid, shrink left; record the answer when valid.
  • State in JavaScript: a Map with map.get(ch) ?? 0, calling delete when a count reaches 0 so map.size is the number of distinct characters; or new Array(26).fill(0) indexed by s.charCodeAt(i) - 97 for lowercase letters. Add a counter such as 'missing' for minimum window substring.
  • Longest substring without repeats: store last index of each char; left = max(left, last[ch] + 1). The max() matters ('abba').
  • Sliding window maximum (asked in a 2026 PhonePe round): a deque of indices with decreasing values gives O(n); a heap gives O(n log n).
  • It works for sums only when all numbers are non-negative; with negatives use prefix sums + Map.
  • Do not call s.slice(left, right + 1) on every step to remember the best window: each call copies the window. Keep bestStart and bestLength, and slice once at the end.

The red pen

Common traps: mistake → fix

  • Mistake: Recompute the window from scratch each step

    Fix: that is O(n·k); update incrementally.

  • Mistake: left = last[ch] + 1 is enough

    Fix: left must never move backwards: use max.

  • Mistake: Sliding window works for 'sum equals k' with negative numbers

    Fix: it does not; shrinking can't be decided.

  • Mistake: Setting a Map count to 0 removes the key

    Fix: the key stays and map.size still counts it; call delete.

Easy to hard

Questions interviewers ask, easy to hard

  1. Longest substring without repeating characters.
  2. Maximum sum of any window of size k.
  3. Minimum window substring that contains all characters of t (with repeats).
  4. Maximum of every window of size k in O(n).

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview