Two pointers and sliding windows
Many array and string problems that look like they need nested loops (O(n²)) can be solved in one pass by moving two indexes cleverly. These two patterns, two pointers and sliding windows, are among the most common in interviews.
Two pointers from both ends
On a sorted array, start one pointer at each end and move them towards each other. Each step rules out a whole row of possibilities:
Container with most water
Given heights of vertical lines, find two lines that hold the most water. Moving the shorter line inward is the only move that could possibly help:
Three numbers that sum to zero
Sort, fix one number, then run two pointers on the rest: O(n²) instead of O(n³):
Fast and slow pointers (same direction)
Both pointers move forward; one reads, the other writes. This is how you modify arrays in place:
Sliding windows
A window is a contiguous range [left, right]. Instead of recomputing each window from scratch, slide it: add the item entering on the right, remove the one leaving on the left.
Fixed-size window
Highest total sales over any 3 consecutive days:
O(n), versus O(n·k) for summing each window separately.
Variable-size window
Grow the window to the right; shrink from the left whenever it breaks a rule. Longest substring without repeating characters:
Shortest subarray with a sum of at least target (positive numbers):
Each element enters and leaves the window at most once, so the total work is O(n), even with the inner while.
Windows with counts: smallest window containing all letters
Recognising the patterns
| Clue in the problem | Try |
|---|---|
| Sorted array, find a pair or triple | Two pointers from both ends |
| Modify an array in place, remove or keep items | Read/write pointers |
| "Contiguous subarray" or "substring" with a constraint | Sliding window |
| Window of fixed size k | Fixed sliding window |
| "Longest/shortest … such that …" | Variable window: grow right, shrink left |
Practice
- Check whether a string can become a palindrome by deleting at most one character (two pointers).
- Find the maximum average of any 4 consecutive numbers.
- Find the length of the longest substring with at most 2 distinct characters.
1.Why does the two-pointer pair search need a sorted array?
2.Why is a variable-size sliding window O(n) even with a nested while loop?
3.Which problem suits a sliding window?