~/learn/Python · Algorithms for interviews

Two pointers and sliding windows

Scan a sequence once instead of comparing every pair.

9 min readlesson 17 of 23two pointerssliding window

why this matters

When a nested loop would take forever on a big list, two pointers or a sliding window gets the same answer in a single pass.

On a sorted sequence, two indexes moving toward each other find pairs in linear time: if the sum is too small move the left pointer up, if too big move the right one down.

python · editable
loading editor…

A sliding window keeps a running summary of a contiguous block: add the entering element, drop the leaving one, never recompute the whole block.

python · editable
loading editor…

Try it: Return the starting index of the best window too.

Note

Variable-size windows grow the right edge while a condition holds and shrink the left edge when it breaks — 'longest substring without repeats' is the classic.

Two pointers

sorted list, find pair summing to 10
  [1, 3, 4, 7, 9]
   ↑           ↑
  sum too small → move left pointer right
  sum too big   → move right pointer left

Common gotcha

Two pointers for pair-sums only works on a sorted list. Sort first, or use a dict instead.

key takeaways

  • Two pointers replace a nested loop on sorted data.
  • A sliding window keeps a running total as it moves.
  • Both visit each element roughly once.

check your understanding

Why is a sliding window faster than recomputing each window's sum?

free practice

Build confidence with a question you can solve without Pro.