Module 2: Two Pointers & Sliding Window·Tutorial 5 of 23 (Step 2.2)
All Tutorials·DSA Roadmap·5 Problems · ~10 hrs

2.2 Sliding Window

Learn what a Sliding Window is, why re-scanning overlapping subarrays wastes work, and master fixed, variable, and frequency-counted windows.

01 Read the story: What & Why
02 Follow the drawing: Visual stepper
03 Practice code: 4 languages + problems
Lessons in this module:2.1 Two Pointers2.2 Sliding Window

1. What Is a Sliding Window?

A Sliding Window is a special form of Two Pointers (left and right) that frames a contiguous subarray or substring [left .. right] like a physical window frame sliding across a wall of numbers or characters.


2. Why Do We Need Sliding Window & How Does It Work?

The Pain Without Sliding Window (O(N * K) or O(N^2))

Suppose you have 100,000 numbers and want the highest sum of any 1,000 consecutive numbers. If you compute sum(nums[0..999]) and then start from scratch to compute sum(nums[1..1000]), you just re-added nums[1..999] (999 numbers!) for no reason.

How Fixed-Size Sliding Window Works (O(N))

When a window of size K shifts 1 step right:

  • Add the 1 new item entering on the right (+ nums[right]).
  • Subtract the 1 old item leaving on the left (- nums[right - K]).
Visual: Fixed Window of Size K = 3 Shifting Right by 1 Step
427193- Drop Left (4)Keep Middle [2, 7, 1]+ Add Right (9)New Window Sum = Old Sum - nums[left] + nums[right] (Only 2 operations!)

How Variable-Size Sliding Window Works (The Caterpillar Rule)

What if the window size isn't fixed—for example, "Find the longest substring with no repeating characters"?

  1. Expand right: Step right forward 1 slot and add s[right] to your window state.
  2. Shrink left while invalid: If adding s[right] broke the rule (e.g., created a duplicate), step left forward and remove s[left] in a while loop until the window is valid again.
  3. Update Best: Compare right - left + 1 against your best answer.

Because both left and right only move forward from 0 to N - 1, every item enters the window once and leaves at most once — O(N) total time!

Visual: Variable Window Caterpillar — Expand Right Until Invalid, Then Shrink Left
1. Expand Right (R++) while valid2. Rule broken? Shrink Left (L++)Both L and R only move forward (0 → N), so total work is at most 2N = O(N)!

Step Through the Visual Drawing: How a Window Slides in O(1)

Click Next below to watch how the window drops the outgoing left element and adds the incoming right element without re-summing the middle:

The Hand-Drawn Step-by-Step Walkthrough
Step 1 / 3

Interactive Step-by-Step Trace: Sliding Window (Expand Right, Shrink Left)

Watch how the window slides across [2, 1, 5, 1, 3, 2] without re-summing the middle:

Step 1: Initial Window of Size K = 3 (Indices 0..2)
in win2L
in win1
in win5R
idx 31
idx 43
window_sum = 2 + 1 + 5 = 8 | best = 8

Our first window [2, 1, 5] has sum 8.

✎ Remember this: Only compute the full sum once for the first window.

3. Basic Operations & Walkthroughs (All 4 Languages)

# 1. Fixed-Size Window: Maximum sum of any subarray of length k
def max_sum_k(nums: list[int], k: int) -> int:
  win_sum = sum(nums[:k])
  best = win_sum
  for right in range(k, len(nums)):
      win_sum += nums[right] - nums[right - k]
      best = max(best, win_sum)
  return best

# 2. Variable-Size Window: Longest Substring Without Repeating Characters
def length_of_longest_substring(s: str) -> int:
  last_seen = {}
  left = best = 0
  for right, ch in enumerate(s):
      if ch in last_seen and last_seen[ch] >= left:
          left = last_seen[ch] + 1
      last_seen[ch] = right
      best = max(best, right - left + 1)
  return best
Pattern: Universal Variable-Size Sliding Window Template

Use whenever you need the longest or shortest contiguous subarray/substring satisfying a monotonic condition (no negative numbers in sum problems!).

left = 0
for right, x in enumerate(nums):
  add_to_window(x)
  while window_breaks_rule():
      remove_from_window(nums[left])
      left += 1
  best = max(best, right - left + 1)
Operation / PatternTimeSpaceNotes
Fixed-Size Window (Length K)O(N)O(1)1 addition + 1 subtraction per step
Variable-Size WindowO(N)O(K)Left and right pointers each move at most N times
Anagram / Frequency WindowO(N)O(1)Uses fixed 26-slot or 128-slot character frequency array

5. Practice On Your Own (Curated Submodule Problems)

0 / 5 Solved
StatusProblemDifficultyComplexityHint?Links & Notes
Maximum Average Subarray I
Fixed-Size Sliding Window
Easy
T: O(N)
S: O(1)
Solve
Longest Substring Without Repeating Characters
Variable-Size Sliding Window
Medium
T: O(N)
S: O(min(N, M))
Solve
Longest Repeating Character Replacement
String Frequency / Anagram Window
Medium
T: O(N)
S: O(1)
Solve
Permutation in String
String Frequency / Anagram Window
Medium
T: O(N)
S: O(1)
Solve
Minimum Window Substring
Variable-Size Sliding Window
Hard
T: O(N)
S: O(1)
Solve