Two Pointers, Sliding Windows & Prefix Sums
The array techniques behind a huge share of interview and contest problems.
Find two numbers in a list of 100,000 that add up to a target. The obvious program tries every pair, about 5 billion of them. Sort the list and walk two fingers in from both ends, and at most 99,999 steps remain. Most array problems in interviews and contests hide a waste like this one, and four patterns remove most of it.
What you’ll learn
- Count the pairs and subarrays a brute force checks, about , and say what that costs for .
- Find a pair with a given sum in a sorted array with two pointers, and explain why no pair is missed.
- Slide a window along an array, growing it on the right and shrinking it on the left, to find the best run of consecutive elements.
- Answer any range-sum question with one subtraction from a prefix-sum array.
- Choose the pattern that fits a new problem from its signals: sorted, contiguous, many range queries, or a small set to choose from.
Every pair, every stretch
Two kinds of questions about arrays come up again and again. Some ask about pairs: are there two values that add up to 46? Others ask about stretches of consecutive elements, called subarrays (or substrings of a string): what is the longest run of letters with no letter repeated, or the best total over 3 days in a row?
The brute force answers both with two nested loops. An array of elements has pairs and subarrays, so both loops do about checks.
def pair_with_sum(a, target): # brute force: try every pair
n = len(a)
for i in range(n):
for j in range(i + 1, n):
if a[i] + a[j] == target:
return i, j
return None # checked all n(n-1)/2 pairsCorrect, short, and hopeless for large .
The list has numbers and no pair hits the target, so the brute force checks every pair. A compiled program does roughly simple steps per second (a rule of thumb). About how many seconds does it take?
Show the answer
50 seconds
pairs, and seconds. Contest time limits are 1–2 seconds, and Python is often 10–100 times slower per step, so this is hopeless. Sorting first (about comparisons) and then walking two pointers inward (at most moves) takes milliseconds.
Two pointers: squeeze from both ends
Take a sorted array and a target sum. Put a pointer on the first element and on the last, and look at :
- Too big? Then is too big even with the smallest partner still available, . No pair can use , so move one step left.
- Too small? Then is too small even with the largest partner, . Move one step right.
- Equal? Found it.
This is the two-pointer technique. Here it is on with target :
| , | Verdict | Move | |
|---|---|---|---|
| 0, 5 | too big | left: 11 has no partner | |
| 0, 4 | too small | right: 1 has no partner | |
| 1, 4 | too big | left | |
| 1, 3 | too small | right | |
| 2, 3 | found | stop |
How to spot it: a sorted array (or one you may sort) and a question about pairs, or triples, with a target.
A cousin moves both pointers in the same direction at different speeds. These fast and slow pointers find the middle of a linked list or detect a cycle in it, as the Linked Lists lesson shows.
Sliding windows: a stretch that crawls
Now questions about consecutive elements. Start with a window of fixed size: the best sum of 3 consecutive values in . The brute force adds 3 numbers for each of the 4 windows. But when the window slides one step, one element enters and one leaves, so one addition and one subtraction update the sum:
The best is , from (inclusive). For a window of size , that is 2 operations per step instead of .
Harder questions have no fixed size: find the longest stretch of a string with no letter repeated. A variable window grows on the right one letter at a time. When the new letter already sits inside the window, the left end moves right until it no longer does. Neither end ever moves back.
In "twopointertricks" the window holds "pointer", indices 3 to 9. The next letter is the 't' at index 10, and the last 't' was at index 7. Where must go?
- It stays at 3
- To index 4, one step right
- To index 8, just past the earlier 't'
- To index 10, starting a fresh window
Show the answer
C. To index 8, just past the earlier 't'
Every window that starts at 7 or earlier and reaches index 10 contains two t's, so jumps to 8 and the window becomes "ert". The letters after the old 't' stay in: throwing them away could lose a longer answer later.
How to spot it: consecutive elements, and a rule that stays satisfied when you cut a stretch shorter. A stretch without repeated letters is still without repeats after you drop letters from its ends; that is what lets the window move only forward.
Prefix sums: subtract two running totals
Suppose the array never changes but questions keep arriving: "what is the sum of , inclusive?" Looping costs up to additions per question. Instead, store running totals once, the prefix sums:
is the sum of the first elements. Everything up to , minus everything before , leaves exactly :
Think first With , which two entries give the sum of , and what is it?
, and indeed . The classic slip drops the last element, .
Two relatives come in the Optimized lesson. Suffix sums run from the right and answer "everything after index ". A difference array does the reverse job: "add to every element of " in two writes, with one prefix pass at the end to rebuild the array.
How to spot it: many sum or count questions about ranges of an array that does not change.
Bits: a whole set in one number
Some problems ask you to choose a group: which of these items fit in the bag, which tasks fill exactly 600 minutes? When there are only a few items, say , trying every group is fine: .
A group of items is an -bit number, a bitmask: bit is 1 exactly when item is in the group. Counting therefore lists every group exactly once, with no recursion and no bookkeeping.
How to spot it: up to about 20 and a question about choosing a subset. Loop over all masks and check each in : about steps for . The same table of constraints tells you when not to: with , only or fits, which is why the other three patterns matter.
| Input size (rule of thumb, 1 s) | What fits |
|---|---|
| up to about 20–25 | : every subset |
| up to about 5,000 | : every pair or subarray |
| up to about | : sort, then two pointers |
| up to about | : one window pass, one prefix pass |
Which pattern fits?
| Signal in the problem | Pattern | Typical cost |
|---|---|---|
| Sorted array (or one you may sort), pairs or triples with a target | Two pointers from both ends | after an sort |
| Contiguous stretch, rule still holds when the stretch gets shorter | Sliding window | |
| Many sum or count questions about ranges of a fixed array | Prefix sums | once, per query |
| Many "add to " updates, read at the end | Difference array | per update, at the end |
| or so, choose a subset | Bitmask enumeration |
A log stores the number of visitors in each of the last minutes. A dashboard then asks questions of the form "how many visitors arrived between minute and minute ?". Which pattern fits?
- Two pointers from both ends
- Prefix sums
- A sliding window that moves to each question's range
- Bitmask enumeration
Show the answer
B. Prefix sums
The array never changes and every question is a range sum: build once ( additions) and answer each question with . About operations instead of up to .
| Optimized lesson | What you will do there |
|---|---|
| The Two-Pointer Technique | Prove that no pair is missed, solve container with most water, trapping rain water and 3SUM, and edit arrays in place with read and write pointers. |
| The Sliding Window Technique | Run fixed and variable windows with counts in hash maps, learn the grow-right, shrink-left template, and prove that one pass costs . |
| Prefix Sums & Suffix Sums | Answer range queries, compute products of all other elements, apply range updates with difference arrays, and count subarrays with sum . |
| Bit Manipulation | Read two's complement, use and , find unpaired values with XOR, and treat subsets as bitmasks. |
Key takeaways
- Trying every pair or every subarray costs about checks: for , nearly a minute even in fast code.
- Two pointers on a sorted array: if the sum is too big, drop the right end; if too small, drop the left end. Each move rules out a whole row of pairs, so at most moves.
- A sliding window grows on the right and shrinks on the left; both ends only move forward, so one pass of at most moves visits every window that matters.
- Prefix sums answer any range sum with one subtraction, , after one pass to build .
- Spot the pattern from its signals: sorted and pairs, two pointers; contiguous with a rule that survives shrinking, a window; many range sums, prefix sums; and subsets, bitmasks.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
is sorted and the target is . The pointers start at and , whose sum is . What happens next?
- moves right, to
- moves left, to : no pair can use
- Both pointers move inward
- The search stops: no pair can reach 16
Show the answer
B. moves left, to : no pair can use
is the smallest sum that can be part of, and it is already too big, so is out. The walk continues , , , and finds .
A sliding window finds the longest stretch of a string without a repeated letter. Which statement about its two pointers is true?
- restarts from each time the window shrinks
- The window keeps the same length throughout
- moves back to the left when the window becomes valid again
- Both pointers only move forward, so the pass makes at most moves
Show the answer
D. Both pointers only move forward, so the pass makes at most moves
visits each index once and only catches up, never passing and never moving back. That is why one pass costs rather than the substrings a brute force checks.
For the prefix sums are . What is the sum of , inclusive?
Show the answer
A.
is and is ; their difference is .
From 18 candidate tasks, you must choose a set whose durations add up to exactly 600 minutes. Which approach fits?
- A sliding window over the tasks in their given order
- Two pointers on the sorted durations
- Try all subsets as bitmasks
- Prefix sums of the durations
Show the answer
C. Try all subsets as bitmasks
The chosen tasks need not be consecutive and there can be any number of them, so this is a subset question with a small : masks, each checked in 18 steps, is under operations.
Given a string of lowercase letters, find the shortest substring that contains every vowel (a, e, i, o, u) at least once. Which approach fits best?
- Pointers that start at both ends of the string and move inward
- A window that grows on the right until all five vowels are inside, then shrinks from the left while they still are
- Prefix counts of each vowel, then test every substring in
- Enumerate subsets of positions as bitmasks
Show the answer
B. A window that grows on the right until all five vowels are inside, then shrinks from the left while they still are
Substrings are contiguous, and a stretch that contains all five vowels still does when it grows. So for each right end the window keeps the shortest valid stretch ending there, in one pass with at most moves.
Go deeper
- The Two-Pointer Technique · Walk in from both ends, or let one pointer chase another.
- The Sliding Window Technique · Fixed and variable windows: from all O(n²) subarrays to a single pass.
- Prefix Sums & Suffix Sums · Precompute once, then answer any range sum in O(1).
- Bit Manipulation · Masks, XOR tricks and whole sets packed into one machine word.
Further reading
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online): chapter 8 (the two pointers method and the sliding window minimum), chapter 9 (range queries) and chapter 10 (bit manipulation).
- S. Halim, F. Halim & S. Effendy, Competitive Programming 4 (2020).