Array Technique

Sliding Window

Maintain a window that slides across an array, adding elements on the right and removing on the left. Converts O(n·k) brute-force subarray problems into O(n) by never recomputing from scratch.

What is the sliding window technique?

A sliding window keeps a range [left, right] over an array or string and moves it forward, updating a running result instead of recomputing from scratch. It turns problems like "maximum sum of k consecutive items" or "longest substring without repeating characters" from O(n²) or worse into O(n).

function longestUniqueSubstring(s) {     // O(n)
  const lastSeen = new Map();
  let left = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    if (lastSeen.get(s[right]) >= left) left = lastSeen.get(s[right]) + 1;   // shrink
    lastSeen.set(s[right], right);
    best = Math.max(best, right - left + 1);
  }
  return best;
}
longestUniqueSubstring("abcabcbb");   // 3 ("abc")

Fixed Window

Window size k stays constant. Slide one step at a time: add rightmost, remove leftmost. Example: max sum of k elements.

Variable Window

Window shrinks when a constraint is violated, expands when it is satisfied. Example: longest substring without repeat.

Fixed window — animated

maxSumFixed([1,3,5,2,8,4,7], k=3)step 1/5

// Array state

1
L
3
[1]
5
R
2
[3]
8
[4]
4
[5]
7
[6]
→ k=3. Initial window [1,3,5]=9, maxSum=9

// Pseudocode

1// Fixed window: max sum of k consecutive elements
2function maxSumFixed(nums, k):
3 windowSum = sum(nums[0..k-1]) // initial window
4 maxSum = windowSum
5 for i from k to len(nums) - 1:
6 windowSum += nums[i] // add new element
7 windowSum -= nums[i - k] // remove old element
8 maxSum = max(maxSum, windowSum)
9 return maxSum // O(n)

Variable window pseudocode

longest-unique.pseudo
1// Variable window: longest substring without repeat
2function longestUnique(s):
3 seen = {} // char → last seen index
4 left = 0, maxLen = 0
5 for right from 0 to len(s) - 1:
6 if s[right] in seen and seen[s[right]] >= left:
7 left = seen[s[right]] + 1 // shrink left
8 seen[s[right]] = right
9 maxLen = max(maxLen, right - left + 1)
10 return maxLen // O(n)

Minimum window substring — trace it

min-window.pseudo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// Trace output

Click ▶ Run to trace execution

Complexity

Max sum fixed window — single passO(n)

Linear time

Longest unique substring — each char added/removed onceO(n)

Linear time

Minimum window substring — two passes totalO(n)

Linear time

Space for fixed window — just running sumO(1)

Constant time

Space for hash map — k = alphabet sizeO(k)

O(k) time

⚠️When NOT to use sliding window
Sliding window requires elements to be added/removed contiguously. It breaks for non-contiguous subsets, problems where the optimal window is not monotone in size, or when constraints reference non-adjacent elements.

🎯 Quick Check

What is the time complexity of finding the max sum subarray of size k using the sliding window technique?

Sliding Window: summary

Key points

  • Fixed-size windows add the new item and subtract the one that left.
  • Variable-size windows expand right, then shrink left while a condition is violated.
  • Keep the window's state (sum, counts, last positions) in variables or a hash map.

Frequently asked questions

›Sliding window vs two pointers?

A sliding window is a two-pointer pattern where both pointers move in the same direction and the range between them matters.