Two pointers and sliding window

The two patterns that turn a nested loop into one pass.

10 min read🧮 Data Structures and Algorithms in Java

Two patterns, one idea: most nested loops over a sequence do not need to be nested. Recognising when is worth more than any individual algorithm, because it turns O(n²) into O(n) in about the same number of lines.

Two pointers

Find two numbers in a sorted array that add to a target. The obvious way tries every pair:

java
for (int i = 0; i < xs.length; i++)
    for (int j = i+1; j < xs.length; j++)
        if (xs[i] + xs[j] == target) return new int[]{xs[i], xs[j]};

The other way starts at both ends and walks inward. If the sum is too small, the only way to increase it is to move the left pointer right; if too large, move the right pointer left:

java
int lo = 0, hi = xs.length - 1;
while (lo < hi) {
    int sum = xs[lo] + xs[hi];
    if (sum == target) return new int[]{xs[lo], xs[hi]};
    if (sum < target) lo++; else hi--;
}

Forty thousand elements, and the only matching pair is the last two:

plaintext
###   nested loops  [79996, 79998]      165 ms
###   two pointers  [79996, 79998]        1 ms

Same answer, 165 times. Each pointer moves at most n times, so the whole thing is one pass.

The precondition is sorted, and it is what makes the reasoning valid: knowing the array is ordered is what tells you which pointer to move. On unsorted data this pattern is wrong, and the answer is a HashSet of what you have seen — O(n) and no sorting.

Sliding window

The same idea where the answer is a contiguous run rather than a pair.

The nested-loop version recomputes the sum of every window from scratch, which is the waste:

java
for (int i = 0; i <= n-k; i++) {
    int sum = 0;
    for (int j = i; j < i+k; j++) sum += xs[j];   // recomputes k additions every time
}

The window version moves the sum instead of rebuilding it — add the element entering, subtract the one leaving:

java
int sum = 0;
for (int i = 0; i < k; i++) sum += xs[i];
int best = sum;
for (int i = k; i < n; i++) {
    sum += xs[i] - xs[i-k];
    best = Math.max(best, sum);
}

O(nk) becomes O(n), and nothing about the code got harder to read.

Variable-size windows are the harder half, and the shape is always the same: grow the window from the right, and shrink from the left while the window is invalid.

java
int lo = 0, best = 0;
Set<Character> inWindow = new HashSet<>();
for (int hi = 0; hi < s.length(); hi++) {
    while (!inWindow.add(s.charAt(hi))) inWindow.remove(s.charAt(lo++));
    best = Math.max(best, hi - lo + 1);
}

That is "the longest substring with no repeated character", and the thing to notice is that lo only ever moves forwards. Both pointers together move at most 2n times, which is why a loop with a while inside it is still O(n) — a fact that looks wrong until you count the total movement rather than the nesting.

Prefix sums: pay once, answer every range in O(1)

A sliding window answers "the best window" in one pass. A different question — "the sum of this range, then that one, then a thousand more" — is a loop per query and O(n·q) in total, until you precompute. A prefix sum array holds the running total up to each index; the sum of any range is then two lookups and a subtraction:

java
long[] prefix = new long[n + 1];                       // prefix[i] = sum of a[0..i-1]; prefix[0] = 0
for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + a[i];
 
long rangeSum(int from, int toExclusive) { return prefix[toExclusive] - prefix[from]; }   // O(1)

n + 1 entries with a leading zero is the shape that avoids the off-by-one at from == 0. It is long because a million ints sum past Integer.MAX_VALUE. And it is a read-only trick: one update to a invalidates every prefix after it, so an array that changes between queries wants a Fenwick tree or a segment tree instead — both are prefix sums that update in O(log n), and both are the interview's follow-up.

Where it turns up in backend work: "requests in the last five minutes" over a per-second counter array is a prefix-sum difference; "does any contiguous run of days sum to exactly the target" becomes "have I seen prefix[j] − target before" with a HashMap of prefix values, which is the sliding window's answer for inputs with negative numbers, where the window's shrink-on-overshoot logic no longer works. The same idea in two dimensions — a 2-D prefix table — answers any rectangle's sum in four lookups.

Recognising the shape

The patterns apply when the answer is a pair or a run, and the sequence has an order you can exploit:

The questionPattern
two elements summing to a target, sortedtwo pointers
is this a palindrometwo pointers, inward
remove duplicates from a sorted array in placetwo pointers, one reading one writing
merge two sorted liststwo pointers, one per list
longest run with some propertysliding window, variable
maximum sum of k consecutivesliding window, fixed
smallest run containing all of Xsliding window, variable

And when they do not apply: when the elements you need are not adjacent and the order gives you nothing. "Any two numbers summing to a target, unsorted" is a hash set. "The k largest" is a heap. Reaching for a window because the input is an array is how you get a wrong answer quickly.

Under the hood: why sequential access is fast on real hardware, not just in Big-O

Two pointers and sliding window are both O(n) in the way this lesson already shows — but on real hardware they are faster than an O(n) hash-based alternative by more than the operation counts alone predict, and the reason is cache locality, which Big-O deliberately cannot see.

A modern CPU does not fetch one array element from main memory at a time — it fetches a whole cache line (typically 64 bytes, so 16 consecutive ints) and keeps it in a small, extremely fast L1 cache. Two pointers walking inward from both ends of an array, or a window's lo/hi sliding forward, both touch memory in a predictable, sequential pattern: xs[lo], xs[lo+1], xs[lo+2], … — exactly the access pattern a CPU's hardware prefetcher is built to detect and stay ahead of, so by the time the loop asks for xs[lo+1] it is very often already sitting in L1 cache from the same fetch that brought in xs[lo]. A HashSet-based alternative for the same problem computes a hash and jumps to whatever bucket that hash lands on — an essentially random location in memory from the CPU's point of view, with no predictable pattern to prefetch, so many of those accesses genuinely wait on a round trip to main memory (an L1 hit is roughly 1 nanosecond; a main-memory access is closer to 100). Both approaches can be O(n); the array-scanning one is frequently several times faster in wall-clock time on the same hardware, purely because of what the CPU can predict — which is exactly why this lesson's own 165× measurement for two pointers versus nested loops is bigger than "quadratic versus linear" alone would explain: the nested loop is also making a worse memory-access pattern (re-scanning), not just doing more comparisons.

The prefix-sum array gets the same benefit twice over: building it is one sequential pass (cache-friendly to write), and answering a range query touches exactly two array slots — no traversal at all, so cache behaviour barely matters for the query itself, only for the one-time build.

Try it yourself

Reason about cache behaviour without a profiler

Two implementations of "does this sorted array contain a value near this other value, within some tolerance": one walks two pointers inward as this lesson shows; the other inserts every element into a HashSet and probes it for each candidate value plus and minus the tolerance. Both are O(n). For an array of ten million integers — far larger than any CPU cache — which one is more likely to show a bigger gap between its Big-O prediction and its measured wall-clock time, and why?

Why the hash-based version's real cost hides outside the operation count

The HashSet version, because every lookup is a jump to a data-dependent, effectively random location in memory — with ten million entries far exceeding any CPU cache, the large majority of those lookups miss L1 and L2 and pay a real main-memory round trip, and Big-O counts that exactly the same as a cache hit: one "operation". The two-pointer version's sequential scan lets the hardware prefetcher stay ahead of the access pattern, so most of its reads are served from cache rather than memory. Both are O(n) "operations", but "operation" in Big-O notation was never a promise that every operation costs the same number of nanoseconds — that is a simplification the model makes on purpose, and it is exactly what "what the notation deliberately throws away" already names in the Big-O lesson, here showing up as a memory-hierarchy effect rather than a dropped constant.

Misconceptions

  • "Two O(n) solutions to the same problem will run in roughly the same time." Big-O counts operations, not nanoseconds, and says nothing about which memory each operation touches — a sequential array scan and a hash-table probe can both be O(n) and differ by several times in wall-clock time on large data, purely from cache behaviour.
  • "Sliding window's inner while loop makes it worse than O(n)." It looks like nested-loop O(n·k) at a glance, but lo only ever moves forward and never resets, so across the whole run it advances at most n times total — the same "count total pointer movement, not loop nesting" argument the lesson already makes, and the same shape that makes amortised analysis (the big-O lesson's subject) work.

Sources

  • Ulrich Drepper, "What Every Programmer Should Know About Memory" — cache lines, prefetching, and the real cost gap between sequential and random memory access.
  • Robert Sedgewick and Kevin Wayne, Algorithms (4th ed.) — two-pointer techniques, sliding windows, and prefix sums.
  • Thomas H. Cormen et al., Introduction to Algorithms (CLRS) — prefix sums and range-query preprocessing.
Progress is saved on this device and to your account when signed in.