Simple Algorithm
Algorithms & Data Structures · Brute Force · 18 min

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 n2/2n^2/2, and say what that costs for n=105n=10^5.
  • 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 nn elements has n(n−1)/2n(n-1)/2 pairs and n(n+1)/2n(n+1)/2 subarrays, so both loops do about n2/2n^2/2 checks.

python
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 pairs

Correct, short, and hopeless for large nn.

Predict before you look

The list has n=100,000n=100{,}000 numbers and no pair hits the target, so the brute force checks every pair. A compiled program does roughly 10810^8 simple steps per second (a rule of thumb). About how many seconds does it take?

Show the answer

50 seconds

n(n−1)/2=4,999,950,000≈5×109n(n-1)/2 = 4{,}999{,}950{,}000\approx5\times10^9 pairs, and 5×109/108=505\times10^9/10^8=50 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 nlog⁡2n≈1.7×106n\log_2 n\approx1.7\times10^6 comparisons) and then walking two pointers inward (at most n−1n-1 moves) takes milliseconds.

Two pointers: squeeze from both ends

Take a sorted array and a target sum. Put a pointer LL on the first element and RR on the last, and look at a[L]+a[R]a[L]+a[R]:

  • Too big? Then a[R]a[R] is too big even with the smallest partner still available, a[L]a[L]. No pair can use a[R]a[R], so move RR one step left.
  • Too small? Then a[L]a[L] is too small even with the largest partner, a[R]a[R]. Move LL one step right.
  • Equal? Found it.

This is the two-pointer technique. Here it is on a=[1,3,4,6,8,11]a=[1,3,4,6,8,11] with target 1010:

LL, RRa[L]+a[R]a[L]+a[R]VerdictMove
0, 51+11=121+11=12too bigRR left: 11 has no partner
0, 41+8=91+8=9too smallLL right: 1 has no partner
1, 43+8=113+8=11too bigRR left
1, 33+6=93+6=9too smallLL right
2, 34+6=104+6=10foundstop
Five sums instead of all 15 pairs. Each move throws away one value for good, so the pointers meet after at most n−1n-1 moves.

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 [2,1,5,1,3,2][2,1,5,1,3,2]. 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:

8 → +1−2  7 → +3−1  9 → +2−5  68\ \xrightarrow{\ +1-2\ }\ 7\ \xrightarrow{\ +3-1\ }\ 9\ \xrightarrow{\ +2-5\ }\ 6

The best is 99, from a[2..4]=5+1+3a[2..4]=5+1+3 (inclusive). For a window of size kk, that is 2 operations per step instead of kk.

Harder questions have no fixed size: find the longest stretch of a string with no letter repeated. A variable window a[L..R]a[L..R] 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.

Check your understanding

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 LL go?

  1. It stays at 3
  2. To index 4, one step right
  3. To index 8, just past the earlier 't'
  4. 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 LL 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 a[l..r]a[l..r], inclusive?" Looping costs up to nn additions per question. Instead, store running totals once, the prefix sums:

P[0]=0,P[i+1]=P[i]+a[i].P[0]=0,\qquad P[i+1]=P[i]+a[i].

P[i]P[i] is the sum of the first ii elements. Everything up to rr, minus everything before ll, leaves exactly a[l..r]a[l..r]:

a[l]+a[l+1]+⋯+a[r]  =  P[r+1]−P[l]a[l]+a[l+1]+\cdots+a[r]\;=\;P[r+1]-P[l]
One subtraction per range query, after one pass to build PP.
Think first With P=[0,5,8,6,14,18,17,24,30,32,41]P=[0,5,8,6,14,18,17,24,30,32,41], which two entries give the sum of a[3..8]a[3..8], and what is it?

P[9]−P[3]=32−6=26P[9]-P[3]=32-6=26, and indeed 8+4−1+7+6+2=268+4-1+7+6+2=26. The classic slip P[8]−P[3]=30−6=24P[8]-P[3]=30-6=24 drops the last element, a[8]=2a[8]=2.

Two relatives come in the Optimized lesson. Suffix sums run from the right and answer "everything after index ii". A difference array does the reverse job: "add vv to every element of a[l..r]a[l..r]" 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 n≤20n\le20, trying every group is fine: 220≈1062^{20}\approx10^6.

A group of nn items is an nn-bit number, a bitmask: bit jj is 1 exactly when item jj is in the group. Counting 0,1,2,…,2n−10,1,2,\dots,2^n-1 therefore lists every group exactly once, with no recursion and no bookkeeping.

How to spot it: nn up to about 20 and a question about choosing a subset. Loop over all 2n2^n masks and check each in O(n)O(n): about 2×1072\times10^7 steps for n=20n=20. The same table of constraints tells you when not to: with n=105n=10^5, only O(n)O(n) or O(nlog⁡n)O(n\log n) fits, which is why the other three patterns matter.

Input size nn (rule of thumb, 1 s)What fits
up to about 20–25O(2n⋅n)O(2^n\cdot n): every subset
up to about 5,000O(n2)O(n^2): every pair or subarray
up to about 10610^6O(nlog⁡n)O(n\log n): sort, then two pointers
up to about 10810^8O(n)O(n): one window pass, one prefix pass
At about 10810^8 simple operations per second in a compiled language. Read nn first: it often names the pattern.

Which pattern fits?

Signal in the problemPatternTypical cost
Sorted array (or one you may sort), pairs or triples with a targetTwo pointers from both endsO(n)O(n) after an O(nlog⁡n)O(n\log n) sort
Contiguous stretch, rule still holds when the stretch gets shorterSliding windowO(n)O(n)
Many sum or count questions about ranges of a fixed arrayPrefix sumsO(n)O(n) once, O(1)O(1) per query
Many "add vv to a[l..r]a[l..r]" updates, read at the endDifference arrayO(1)O(1) per update, O(n)O(n) at the end
n≤20n\le20 or so, choose a subsetBitmask enumerationO(2n⋅n)O(2^n\cdot n)
Signals, not rules: always check that the waste the pattern removes is really there.
Check your understanding

A log stores the number of visitors in each of the last 10610^6 minutes. A dashboard then asks 10510^5 questions of the form "how many visitors arrived between minute ll and minute rr?". Which pattern fits?

  1. Two pointers from both ends
  2. Prefix sums
  3. A sliding window that moves to each question's range
  4. Bitmask enumeration
Show the answer

B. Prefix sums

The array never changes and every question is a range sum: build PP once (10610^6 additions) and answer each question with P[r+1]−P[l]P[r+1]-P[l]. About 1.1×1061.1\times10^6 operations instead of up to 101110^{11}.

Optimized lessonWhat you will do there
The Two-Pointer TechniqueProve 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 TechniqueRun fixed and variable windows with counts in hash maps, learn the grow-right, shrink-left template, and prove that one pass costs O(n)O(n).
Prefix Sums & Suffix SumsAnswer range queries, compute products of all other elements, apply range updates with difference arrays, and count subarrays with sum kk.
Bit ManipulationRead two's complement, use x&(x−1)x\mathbin{\&}(x-1) and x&(−x)x\mathbin{\&}(-x), find unpaired values with XOR, and treat subsets as bitmasks.
In the Optimized lessons each pattern gets its code, its correctness proof and its classic problems.

Key takeaways

  • Trying every pair or every subarray costs about n2/2n^2/2 checks: 5×1095\times10^9 for n=105n=10^5, 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 n−1n-1 moves.
  • A sliding window grows on the right and shrinks on the left; both ends only move forward, so one pass of at most 2n2n moves visits every window that matters.
  • Prefix sums answer any range sum with one subtraction, P[r+1]−P[l]P[r+1]-P[l], after one pass to build PP.
  • 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; n≤20n\le20 and subsets, bitmasks.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

a=[2,5,7,9,12,15]a=[2,5,7,9,12,15] is sorted and the target is 1616. The pointers start at 22 and 1515, whose sum is 1717. What happens next?

  1. LL moves right, to 55
  2. RR moves left, to 1212: no pair can use 1515
  3. Both pointers move inward
  4. The search stops: no pair can reach 16
Show the answer

B. RR moves left, to 1212: no pair can use 1515

2+152+15 is the smallest sum that 1515 can be part of, and it is already too big, so 1515 is out. The walk continues 2+12=142+12=14, 5+12=175+12=17, 5+9=145+9=14, and finds 7+9=167+9=16.

Question 2

A sliding window finds the longest stretch of a string without a repeated letter. Which statement about its two pointers is true?

  1. RR restarts from LL each time the window shrinks
  2. The window keeps the same length throughout
  3. LL moves back to the left when the window becomes valid again
  4. Both pointers only move forward, so the pass makes at most 2n2n moves
Show the answer

D. Both pointers only move forward, so the pass makes at most 2n2n moves

RR visits each index once and LL only catches up, never passing R+1R+1 and never moving back. That is why one pass costs O(n)O(n) rather than the n(n+1)/2n(n+1)/2 substrings a brute force checks.

Question 3

For a=[4,2,7,1,5]a=[4,2,7,1,5] the prefix sums are P=[0,4,6,13,14,19]P=[0,4,6,13,14,19]. What is the sum of a[1..3]a[1..3], inclusive?

  1. P[4]−P[1]=10P[4]-P[1]=10
  2. P[3]−P[1]=9P[3]-P[1]=9
  3. P[4]−P[2]=8P[4]-P[2]=8
  4. P[4]=14P[4]=14
Show the answer

A. P[4]−P[1]=10P[4]-P[1]=10

P[4]P[4] is a[0]+⋯+a[3]a[0]+\cdots+a[3] and P[1]P[1] is a[0]a[0]; their difference is 2+7+1=102+7+1=10.

Question 4

From 18 candidate tasks, you must choose a set whose durations add up to exactly 600 minutes. Which approach fits?

  1. A sliding window over the tasks in their given order
  2. Two pointers on the sorted durations
  3. Try all 218=262,1442^{18}=262{,}144 subsets as bitmasks
  4. Prefix sums of the durations
Show the answer

C. Try all 218=262,1442^{18}=262{,}144 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 nn: 2182^{18} masks, each checked in 18 steps, is under 5×1065\times10^6 operations.

Question 5

Given a string of 10510^5 lowercase letters, find the shortest substring that contains every vowel (a, e, i, o, u) at least once. Which approach fits best?

  1. Pointers that start at both ends of the string and move inward
  2. A window that grows on the right until all five vowels are inside, then shrinks from the left while they still are
  3. Prefix counts of each vowel, then test every substring in O(1)O(1)
  4. 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 2n2n moves.

Go deeper

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).