Two Pointers — two fingers, one pass
How two indices moving through an array or string turn quadratic searches into linear scans: converging pointers, reader/writer pointers, parallel pointers over two sequences, three-way partitioning and the tortoise and the hare — with proofs, Python implementations and eight working labs.
AChapter introduction
Prerequisites
You should be able to write Python loops and functions, index into lists and strings (a[i], s[-1], slicing), and read Big-O statements such as "O(n) time, O(1) extra space". The Time & Space Complexity chapter covers everything needed. Knowing that sorting costs O(n log n) will help in Sections C and H.
Learning objectives
After this chapter you will be able to:
- Define the two-pointer technique precisely and name its four families: converging, same-direction (reader/writer, fast/slow), two-sequence and partition.
- Explain why a pointer may be moved — the elimination argument — and prove correctness with a loop invariant.
- Prove the O(n) bound with the "each pointer only moves one way" (potential-function) argument.
- Implement, from scratch in Python, pair-sum, palindrome check, in-place de-duplication, merge, Container With Most Water, 3Sum, Dutch-national-flag partitioning and Floyd's cycle detection.
- Choose between two pointers, hashing, binary search, sliding windows and prefix sums, and recognise when two pointers is the wrong tool.
- Avoid the classic bugs: off-by-one loop conditions, infinite loops, missing duplicate skips and running converging pointers on unsorted data.
BFundamental understanding
What is the two-pointer technique?
A pointer here is not a memory address. It is an integer index (or a reference to a node) that marks a position in a sequence. The technique keeps two such positions and moves them according to the values they currently see. The USACO Guide describes it as iterating two pointers across an array to track indices that satisfy some condition [1]. Purdue's competitive-programming course gives the same definition: maintain two indices into one array or two arrays, and move them based on the values they point to [3].
Why the technique exists
Many array and string questions are about pairs: two values that add up to a target, two walls that hold the most water, two characters that must match, one item from each of two lists. There are n(n−1)/2 pairs among n items, so checking them all is quadratic. Purdue's slides make the point with Container With Most Water: the obvious solution tries all pairs in O(n²), while two pointers moving inward from both ends solve it in linear time [3]. The technique exists to prune the pair space without missing the answer.
What came before, and where the idea comes from
The technique has no single inventor. It is a pattern that runs through classical algorithms, and you have probably used it already:
- Merging two sorted arrays, the core of mergesort, walks one index through each input and repeatedly copies the smaller front element, in linear time [6][7].
- Quicksort partitioning scans index
ifrom the left and indexjfrom the right, swapping out-of-place items until the pointers cross [4][5]. - Dijkstra's Dutch National Flag problem, a structured-programming exercise in program derivation and proof, partitions items of three colours in one pass with three indices [10][11][17].
- Floyd's "tortoise and hare" cycle-finding algorithm moves two pointers at different speeds through a sequence. Knuth credited the idea to Robert W. Floyd, though the attribution is disputed [12][13].
Interview culture later gave the shared idea a name, "two pointers". Competitive-programming references now teach it as a technique in its own right [1][2][3].
Fundamental principles (terminology introduced gradually)
| Term | Meaning | Example |
|---|---|---|
| Pointer | An index (or node reference) marking a position. | lo = 0 |
| Window / active region | The positions that may still hold an answer. | A[lo..hi] |
| Monotone movement | A pointer only ever moves one way, so it never revisits a position. | lo only increases |
| Elimination step | One comparison proves that a position cannot be part of any remaining answer, so the pointer leaves it. | sum too small ⇒ discard A[lo] |
| Invariant | A statement that is true before every iteration and gives correctness. | "if a pair exists, it lies in [lo..hi]" |
| Termination condition | When the active region is empty. | lo < hi fails |
CThe problem statement
We anchor the chapter on the canonical problem, pair sum in a sorted array, and then generalise. It appears as LeetCode 167 "Two Sum II", in CSES "Sum of Two Values" and in Laaksonen's handbook as the 2SUM problem [2][1][23].
Output: indices i < j with A[i] + A[j] = T, or "none".
Constraints (typical): n up to 10⁵–10⁶; extra memory should be O(1); each element may be used at most once.
Why the naive approach is inefficient
The brute-force solution tests every pair, for i … for j > i, which is n(n−1)/2 = Θ(n²) checks in the worst case. Our own measurement in Section I gives 499,500 pair checks for n = 1000. For n = 10⁶ that is about 5 × 10¹¹ checks, which takes minutes to hours even in a compiled language and far longer in Python. Illustration
Limitations of the obvious alternatives
| Alternative | Time | Extra space | Limitation |
|---|---|---|---|
| Brute force, all pairs | Θ(n²) | O(1) | Too slow beyond about 10⁴ elements. |
| Binary search for T − A[i] for each i | O(n log n) | O(1) | Correct, but slower than linear and fiddly when values repeat. Laaksonen notes this alternative [2]. |
| Hash set of values seen so far | O(n) expected | O(n) | Uses linear memory, expected rather than worst-case O(1) lookups [18], and ignores the sortedness we were given. |
| Two pointers | O(n) worst case | O(1) | Needs sorted input (or permission to sort). |
How two pointers improves the solution
Put lo at the smallest value and hi at the largest, and look at s = A[lo] + A[hi]:
- If s < T, then
A[lo]paired with the largest remaining value is still too small, so it is too small with every remaining partner. Discard it:lo += 1. - If s > T, then
A[hi]paired with the smallest remaining value is still too big, so discard it:hi -= 1. - If s = T, we are done.
Each step removes one element from consideration, so there are at most n − 1 steps. The Purdue slides note that the loop runs while first < second, so no element is used twice, and that each step moves one pointer, so the run time is linear [3]. Including an initial sort, the total is O(n log n), which matches the USACO Guide's analysis [1][2].
DVisual whiteboard explanations
- Converging:
lostarts at index 0 andhiat n−1. They move toward each other, and the loop ends when they meet. - Same direction:
readvisits every element, andwritemarks where the next kept element goes. Everything left ofwriteis final. - Two sequences:
iwalks list A andjwalks list B. The smaller front value goes to the output. - Partition: three indices split the array into four zones (0s, 1s, unknown, 2s) that change in one pass.
The most important picture in this chapter is the next one. It explains why converging pointers cannot miss a pair.
- Start in the top-right corner (0, 5), the smallest row index paired with the largest column. The sum is 12 > 10. Every other cell in column 5 lies in a lower row, so its sum is at least 12. The whole of column 5 is useless and gets struck:
hi −= 1. - Move left to (0, 4): 9 < 10. Every other cell in row 0 is ≤ 9, so the whole row 0 is struck.
- Steps 3 and 4 strike column 4 and row 1 in the same way. Step 5 lands on 10, the answer.
A[lo..hi] shrinks by exactly one cell per step, from 6 cells to 2. Grey cells never come back. Each red sentence is the elimination argument for that step. Compare it with the matrix in Figure D.2: the steps match one-for-one.
Technical interpretation: the loop invariant "if an answer exists, both of its indices lie in [lo..hi]" holds before every step. Section G proves it.A[write] = A[read]readscans indices 1…9 and compares each value with the last kept value,A[write−1].- A new value (first occurrences at indices 2, 5, 7, 9) is copied to
A[write], andwriteadvances. - At the end,
write = 5is the number of distinct values. Positions 5…9 hold leftovers that the caller ignores. This is exactly LeetCode 26's contract [23].
A[0..write−1] is the de-duplicated version of A[0..read−1]". It needs n−1 comparisons, at most n−1 writes and O(1) extra memory.
EInteractive labs
Every lab follows the same pattern. Edit the input and press Load; the algorithm runs once and records every state. Then use Play / Pause, Next, Prev and Reset (or drag the speed slider) to walk through it. The status bar explains each decision in words. Colours follow the chapter legend: yellow = active pointer, green = result, red = mismatch / eliminated, purple = anchor / relation, grey = consumed.
FInternal working
Memory representation: what a "pointer" really is in Python
In CPython a list is a variable-length array: a contiguous block of references to other objects, plus a header that stores the length. That is why indexing a[i] takes constant time, independent of i and of the list's length [25][18]. A two-pointer "pointer" is just a Python int used as an index into that block. Moving it (lo += 1) is O(1), and reading a[lo] is O(1). This random access is what converging pointers need, because they must reach the right end immediately.
lo and hi are plain integers. The address of slot k is the base address plus k times the slot size, which is why access is O(1). Python strings are immutable [20]: two pointers can read a string in place (Lab 2), but algorithms that swap characters (reversal) must first convert to a list with list(s) and join back with "".join(...), which costs O(n) extra space.
Technical interpretation: two-pointer algorithms on arrays assume O(1) random access. On a singly linked list you can only move forward, so the converging pattern does not apply directly. The same-direction (fast/slow) pattern does, and it is the basis of Floyd's algorithm.Execution flow of the converging loop
lo right, or move hi left. Both moves shrink hi − lo by one, so the loop must stop after at most n − 1 iterations.
Technical interpretation: the quantity Φ = hi − lo is a variant (a potential function). It is a non-negative integer that strictly decreases on every iteration, which proves termination and bounds the running time at the same time.State changes, step by step (pair sum)
- Initialise
lo = 0,hi = n − 1. The window holds the whole array. For n ≤ 1 the loop never runs and we returnNone. - Read
A[lo]andA[hi]: two O(1) index operations. - Compute
s = A[lo] + A[hi]. Python ints are arbitrary precision, so there is no overflow. In C or Java, use 64-bit arithmetic or compareA[lo]withT − A[hi]instead. - Decide with one three-way comparison against
T. - Mutate exactly one pointer, by ±1. Nothing else changes, and the array itself is never modified.
- Re-test the loop condition
lo < hi. When it fails, the window contains fewer than two elements, so no pair remains.
Internal working of the other families
| Family | State | Rule per step | Stops when | Who moves |
|---|---|---|---|---|
| Converging | lo, hi | compare f(A[lo], A[hi]) with goal; drop the side proven useless | lo ≥ hi | exactly one (or both on a match) |
| Reader/writer | read, write | read always advances; write advances only when A[read] is kept | read = n | read every step, write sometimes |
| Two sequences | i, j | advance the pointer at the smaller front value (merge: and emit it) | one list exhausted | one per step (both on a tie in intersection) |
| Partition (DNF) | lt, i, gt | classify A[i]: swap to the left zone, the right zone, or leave it | i > gt | (lt and i), or gt, or i |
| Fast/slow (Floyd) | slow, fast | slow takes one step, fast takes two | they meet or fast reaches the end | both |
Edge cases every implementation must handle
| Case | What happens | Correct behaviour |
|---|---|---|
| Empty input / one element | hi = −1 or 0; lo < hi is false at once | return "none" without indexing |
| All elements equal | e.g. [5,5,5], T = 10 | first check succeeds; with lo < hi the same element is never used twice |
| Duplicates (3Sum) | equal anchors or second values repeat triplets | skip equal neighbours after sorting (Lab 7) |
| Negative numbers | sorted order still holds | converging pair-sum still works; the sliding window technique for subarray sums does not (Section L) |
| Unsorted input | the elimination argument is false | sort first (if the original indices are not required) or use a hash map |
| Strings with punctuation / Unicode | pointers stop on non-letters | skip with str.isalnum() and compare .lower() (or .casefold()) [20] |
GMathematical foundation
G.1 Correctness of converging pair-sum (loop invariant)
Initialisation. lo = 0 and hi = n−1, so every pair is inside the window.
Maintenance. Suppose s = A[lo] + A[hi] < T. For any k with lo < k ≤ hi, sortedness gives A[k] ≤ A[hi], so
A[lo] + A[k] ≤ A[lo] + A[hi] < T.So lo pairs successfully with no index in the window, and removing it (lo ← lo + 1) keeps I true. The case s > T is symmetric: for any k with lo ≤ k < hi, A[k] + A[hi] ≥ A[lo] + A[hi] > T, so we can remove hi.
Termination. The variant Φ = hi − lo starts at n − 1 and drops by exactly 1 per iteration that does not return. When lo ≥ hi, the window holds no pair, so by I no solution existed and returning "none" is correct. If we return early, the returned pair is correct by construction. ∎
This is the formal version of the matrix picture in Figure D.2. Each comparison removes a row (index lo) or a column (index hi) of the upper-triangular sum matrix, and the rows and columns are sorted. The same staircase argument underlies searching a row- and column-sorted matrix in O(m+n). Illustration
G.2 The amortized (monotone-pointer) bound
For the same-direction and two-sequence families, the loop body may not move both pointers every time, so "Φ drops by one" is replaced by a counting argument. Each pointer only increases and never exceeds its sequence length, so the total number of increments is at most n per pointer. Laaksonen gives this argument for the subarray-sum example: the left pointer moves O(n) steps in total and the right pointer, which only moves to the right, also moves O(n) steps, so the algorithm is O(n) even though one iteration may move a pointer many times [2]. The USACO Guide uses the same reasoning for its sliding-window example: both pointers move at most N times, so the total is O(N) [1].
total work = Σiterations (pointer moves + O(1)) ≤ (np + nq) + O(#iterations) = O(n)G.3 Container With Most Water: why moving the shorter wall is safe
Let area(i, j) = (j − i) · min(hi, hj). Suppose hlo ≤ hhi. For any k with lo < k < hi:
area(lo, k) = (k − lo) · min(hlo, hk) ≤ (k − lo) · hlo < (hi − lo) · hlo = area(lo, hi).Every container that keeps wall lo and is narrower than the current one is strictly worse than the current one, which we have already recorded. So lo can be dropped without losing the optimum. Purdue's slides state exactly this insight: any container [i, k] inside [i, j] holds no more than the current container when h[i] is the shorter wall [3].
[1, 8, 6, 2, 5, 4, 8, 3, 7], the first container (0, 8) has area 8. Wall 0 has height 1, so containers (0, 3), (0, 5) and (0, 7) can hold at most 3, 5 and 7. All are below 8 and are skipped. Run Lab 4 to see the remaining steps reach the optimum, 49 (walls 1 and 8).
Technical interpretation: this is an exchange or dominance argument. Each step discards a set of pairs that are each dominated by a pair already evaluated, so the maximum over evaluated pairs equals the global maximum.G.4 Dutch National Flag invariant
With pivot class "1", Dijkstra's three-way partition keeps four zones. Sedgewick and Wayne state the invariant as: a[lo..lt−1] less than v, a[lt..i−1] equal to v, a[i..gt] not yet examined, and a[gt+1..hi] greater than v [4][5]. Each iteration either advances i or decreases gt, so the unknown zone gt − i + 1 shrinks by one every time. That gives at most n iterations, a single pass, and Θ(n) examinations [10].
G.5 Floyd's cycle detection: why the pointers meet, and where
Iterate xk+1 = f(xk) on a finite set. The sequence eventually repeats: a tail of length μ leads into a cycle of length λ [12]. The tortoise is at xk and the hare at x2k. They coincide exactly when k ≥ μ and λ divides k, and the first such k is at most μ + λ [14]. If the meeting happens a steps into the cycle, then μ + a = k is a multiple of λ. So walking μ more steps from the meeting point lands on the entrance, and that is why phase 2 restarts one pointer at x0 and moves both at speed 1 [12]. The algorithm uses O(λ + μ) steps and O(1) memory [12].
HOperations and complexity analysis
Below, n is the input length, and for two-sequence problems m and n are the two lengths. "Auxiliary space" excludes the input and the output. Times assume O(1) indexing and comparison, which holds for Python lists of numbers [18].
| Operation | Best | Average | Worst | Aux. space | Why |
|---|---|---|---|---|---|
| Pair sum, sorted input | Θ(1) | O(n) | Θ(n) | Θ(1) | best: first pair matches; worst: Φ = hi−lo falls from n−1 to 0 |
| Pair sum, unsorted (sort first) | Θ(n log n)* | Θ(n log n) | Θ(n log n) | O(n) | sorting dominates [2]; Timsort exploits order already present, so nearly sorted input sorts much faster [19]. (*on random data) |
| Palindrome check | Θ(1) | O(n) | Θ(n) | Θ(1) | first mismatch stops early; each step consumes ≥ 1 character |
| Reverse in place | Θ(n) | Θ(n) | Θ(n) | Θ(1) | exactly ⌊n/2⌋ swaps |
| Remove duplicates / move zeros / remove value | Θ(n) | Θ(n) | Θ(n) | Θ(1) | read visits every index once, write ≤ read |
| Merge two sorted lists | Θ(m+n) | Θ(m+n) | Θ(m+n) | Θ(m+n) output | between min(m,n) and m+n−1 compares [6][7] |
| Intersect sorted lists | Θ(min(m,n)) | O(m+n) | Θ(m+n) | Θ(1) + output | each step advances ≥ 1 pointer [16] |
| Container With Most Water | Θ(n) | Θ(n) | Θ(n) | Θ(1) | no early exit: exactly n−1 evaluations |
| Dutch flag / Sort Colors | Θ(n) | Θ(n) | Θ(n) | Θ(1) | unknown zone shrinks by 1 per iteration [10] |
| 3Sum (all triplets) | Θ(n log n) | Θ(n²) | Θ(n²) | O(n) for the sort | n anchors × Θ(n) pair scan [9]; best case: the early break when A[i] > 0 |
| Floyd cycle detection | Θ(μ+λ) | Θ(μ+λ) | Θ(μ+λ) | Θ(1) | meeting index ≤ μ+λ; phase 2 takes μ steps [12][14] |
Reading the notations
For converging pair-sum the worst-case running time is Θ(n). It is O(n) because Φ bounds the iterations, and it is Ω(n) because with no solution every element must be discarded one at a time. The best case is Θ(1). So the tightest statement valid for all inputs is O(n), and Ω(1) is the matching lower bound. A stronger fact also holds: any correct algorithm must look at Ω(n) elements in the worst case, because an unread element could complete the target. Two pointers are therefore asymptotically optimal for sorted pair-sum. Illustration
Recurrences? Amortization?
Two-pointer loops are iterative, so no recurrence is needed. Their analysis is an aggregate amortized argument: one iteration of a sliding-window loop may move lo many times, but the total over the whole run is at most n, so the average cost per iteration is O(1) [2]. Recurrences appear only when two pointers is used inside divide and conquer. Mergesort's T(n) = 2T(n/2) + Θ(n) has a linear two-pointer merge as its Θ(n) term, which gives Θ(n log n) overall [7].
Time–space trade-offs and theory versus Python
- Sort + two pointers versus hashing. On unsorted data, a one-pass hash map solves pair-sum in expected O(n) time with O(n) memory. Sorting first costs O(n log n) time, and the pointer phase then needs only O(1) extra memory. The sort itself either mutates the caller's list (
list.sort()) or copies it (sorted()) [19]. Dict and set operations are O(1) on average but O(n) in the worst case [18]. - Constant factors in CPython. Each
lo += 1creates or reuses an int object and runs bytecode, so a two-pointer loop in pure Python does roughly 10⁷ simple steps per second. Built-ins written in C (sorted,list.reverse,s[::-1],heapq.merge's internals) are much faster per element. For example,s == s[::-1]is often faster than a hand-written palindrome loop even though it allocates O(n) extra memory. Big-O predicts growth, not wall-clock winners at small n. Illustration - Slicing is not free.
a[i:j]copies j − i references andx in listis O(n) [18]. Writingif target - a[i] in a[i+1:]inside a loop silently turns a "two pointer" solution back into O(n²). list.pop(0)andinsert(0, x)are O(n) [18]. Moving an index is the O(1) way to "remove from the front".
IPython implementation
Everything below comes from one companion module, two_pointers.py. It was executed in full, including 3,000 randomized cross-checks against brute force and built-ins. The output shown at the end of this section is the real output.
I.1 Converging pointers: pair sum (with an optional trace)
def pair_sum_sorted(nums: List[int], target: int,
trace: bool = False) -> Optional[Tuple[int, int]]:
"""Return indices (i, j), i < j, with nums[i] + nums[j] == target.
Precondition: nums is sorted in non-decreasing order. O(n) time, O(1) space."""
lo, hi = 0, len(nums) - 1
step = 0
while lo < hi: # window [lo..hi] still has >= 2 items
s = nums[lo] + nums[hi]
step += 1
if trace:
print(f"step {step}: lo={lo} hi={hi} sum={nums[lo]}+{nums[hi]}={s}", end=" ")
if s == target:
if trace: print("-> FOUND")
return lo, hi
if s < target: # nums[lo] is too small for EVERY partner
if trace: print("-> too small, lo += 1")
lo += 1
else: # nums[hi] is too big for EVERY partner
if trace: print("-> too big, hi -= 1")
hi -= 1
return None
Line by line. lo, hi = 0, len(nums) - 1 opens the window over the whole list (for an empty list, hi = −1 and the loop is skipped). while lo < hi requires two distinct indices, so an element is never paired with itself. s < target ⇒ lo += 1 and s > target ⇒ hi -= 1 are the two elimination steps proved in G.1. Returning a tuple of indices (rather than values) matches LeetCode 167's contract, apart from its 1-based indexing [23].
Dry-run table: nums = [1, 3, 4, 6, 8, 11], target = 10
| Step | lo | hi | nums[lo] | nums[hi] | sum | Decision | Window after |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 5 | 1 | 11 | 12 | > 10 → hi −= 1 | [0..4] |
| 2 | 0 | 4 | 1 | 8 | 9 | < 10 → lo += 1 | [1..4] |
| 3 | 1 | 4 | 3 | 8 | 11 | > 10 → hi −= 1 | [1..3] |
| 4 | 1 | 3 | 3 | 6 | 9 | < 10 → lo += 1 | [2..3] |
| 5 | 2 | 3 | 4 | 6 | 10 | found → (2, 3) | — |
I.2 Converging pointers on strings and greedy variants
def is_palindrome(s: str) -> bool:
"""LeetCode 125: ignore non-alphanumerics, compare case-insensitively. O(n), O(1)."""
lo, hi = 0, len(s) - 1
while lo < hi:
if not s[lo].isalnum():
lo += 1
elif not s[hi].isalnum():
hi -= 1
elif s[lo].lower() != s[hi].lower():
return False
else:
lo += 1
hi -= 1
return True
def reverse_in_place(a: list) -> None:
"""Swap symmetric pairs until the pointers meet. floor(n/2) swaps."""
lo, hi = 0, len(a) - 1
while lo < hi:
a[lo], a[hi] = a[hi], a[lo]
lo += 1
hi -= 1
def max_area(height: List[int]) -> int:
"""LeetCode 11, Container With Most Water. O(n), O(1)."""
lo, hi = 0, len(height) - 1
best = 0
while lo < hi:
width = hi - lo
best = max(best, width * min(height[lo], height[hi]))
if height[lo] < height[hi]: # the shorter wall limits every narrower
lo += 1 # container that keeps it -> discard it
else:
hi -= 1
return best
str.isalnum() returns true only for letters and digits, and str.lower() gives a case-insensitive comparison [20]. Note the if / elif chain: each iteration moves at least one pointer, which guarantees progress. In max_area the comparison height[lo] < height[hi] decides which wall is provably useless (G.3). On ties either pointer may move.
I.3 Anchor + converging: 3Sum
def three_sum(nums: List[int]) -> List[List[int]]:
"""LeetCode 15: all unique triplets summing to 0. O(n^2) time, O(1) extra
besides the output and the sort."""
a = sorted(nums) # Timsort: O(n log n)
n = len(a)
out = []
for i in range(n - 2):
if a[i] > 0: # smallest of the three is positive -> stop
break
if i > 0 and a[i] == a[i - 1]: # skip duplicate anchors
continue
lo, hi = i + 1, n - 1
while lo < hi:
s = a[i] + a[lo] + a[hi]
if s < 0:
lo += 1
elif s > 0:
hi -= 1
else:
out.append([a[i], a[lo], a[hi]])
lo += 1
hi -= 1
while lo < hi and a[lo] == a[lo - 1]: # skip duplicate seconds
lo += 1
return out
Why only lo skips duplicates: once a triplet is recorded we move both pointers. If a[lo] now repeats, the sum with the same anchor can only be zero again with the same a[hi] value, so skipping repeated lo values is enough to prevent duplicate triplets. The randomized test compares the output, as a list, against a set built from itertools.combinations, so any duplicate would fail.
I.4 Same-direction pointers: reader/writer and fast/slow
def remove_duplicates(nums: List[int]) -> int:
"""LeetCode 26: in a sorted list keep the first copy of each value.
Returns k; nums[:k] holds the unique values. O(n), O(1)."""
if not nums:
return 0
write = 1 # nums[:write] is the de-duplicated prefix
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]: # a value we have not kept yet
nums[write] = nums[read]
write += 1
return write
def move_zeroes(nums: List[int]) -> None:
"""LeetCode 283: move zeros to the end, keep the order of non-zeros."""
write = 0
for read in range(len(nums)):
if nums[read] != 0:
nums[write], nums[read] = nums[read], nums[write]
write += 1
def find_duplicate(nums: List[int]) -> int:
"""LeetCode 287 via Floyd's tortoise and hare. nums has n+1 values in 1..n.
Treat i -> nums[i] as a linked list; the duplicate is the cycle entrance."""
slow = fast = nums[0]
while True: # phase 1: meet inside the cycle
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0] # phase 2: find the entrance (mu)
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
Dry-run table: remove_duplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])
| read | nums[read] | nums[write−1] | new? | action | write after |
|---|---|---|---|---|---|
| 1 | 0 | 0 | no | skip | 1 |
| 2 | 1 | 0 | yes | nums[1] = 1 | 2 |
| 3, 4 | 1, 1 | 1 | no | skip | 2 |
| 5 | 2 | 1 | yes | nums[2] = 2 | 3 |
| 6 | 2 | 2 | no | skip | 3 |
| 7 | 3 | 2 | yes | nums[3] = 3 | 4 |
| 8 | 3 | 3 | no | skip | 4 |
| 9 | 4 | 3 | yes | nums[4] = 4 | 5 = k |
I.5 Two sequences and three-way partition
def merge_sorted(a: List[int], b: List[int]) -> List[int]:
"""Merge two sorted lists into a new sorted list. Theta(len(a)+len(b))."""
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]: # '<=' keeps the merge stable
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
out.extend(a[i:]) # at most one of these is non-empty
out.extend(b[j:])
return out
def intersect_sorted(a: List[int], b: List[int]) -> List[int]:
"""Common values of two sorted lists (with multiplicity), O(len(a)+len(b))."""
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] == b[j]:
out.append(a[i]); i += 1; j += 1
elif a[i] < b[j]:
i += 1
else:
j += 1
return out
def is_subsequence(s: str, t: str) -> bool:
"""LeetCode 392: can s be obtained from t by deleting characters?"""
i = 0
for ch in t:
if i < len(s) and s[i] == ch:
i += 1
return i == len(s)
def sort_colors(nums: List[int]) -> None:
"""LeetCode 75. Invariant: [0,lt) == 0, [lt,i) == 1, [i,gt] unknown, (gt,n) == 2."""
lt, i, gt = 0, 0, len(nums) - 1
while i <= gt:
if nums[i] == 0:
nums[lt], nums[i] = nums[i], nums[lt]
lt += 1; i += 1
elif nums[i] == 2:
nums[gt], nums[i] = nums[i], nums[gt]
gt -= 1 # do NOT advance i: the swapped-in value is unexamined
else:
i += 1
merge_sorted uses <= so that equal keys from a come before those from b. This is the stability property that makes mergesort stable. Only one of the final extend calls adds anything. In sort_colors the asymmetry is deliberate: after swapping with gt the incoming value has not been examined, so i stays where it is.
I.6 Sample run (real output)
$ python two_pointers.py
== pair_sum_sorted trace ==
step 1: lo=0 hi=5 sum=1+11=12 -> too big, hi -= 1
step 2: lo=0 hi=4 sum=1+8=9 -> too small, lo += 1
step 3: lo=1 hi=4 sum=3+8=11 -> too big, hi -= 1
step 4: lo=1 hi=3 sum=3+6=9 -> too small, lo += 1
step 5: lo=2 hi=3 sum=4+6=10 -> FOUND
(2, 3)
None
None None
== brute force vs two pointers (no solution, worst case) ==
n= 10 brute-force pairs checked= 45 two-pointer iterations<= 9
n= 100 brute-force pairs checked= 4950 two-pointer iterations<= 99
n= 1000 brute-force pairs checked= 499500 two-pointer iterations<= 999
== strings ==
True False True
olleh
== container / 3sum / trap / squares ==
49
[[-1, -1, 2], [-1, 0, 1]]
[[0, 0, 0]]
6
[0, 1, 9, 16, 100]
== same direction ==
5 [0, 1, 2, 3, 4]
[1, 3, 12, 0, 0]
2 3
== two sequences ==
[1, 2, 3, 4, 7, 8, 9, 10, 12]
[2, 2, 5]
True False
== partition ==
[0, 0, 1, 1, 2, 2]
all randomized checks passed
I.7 Error handling and input validation
Library-quality code should check its preconditions, because a converging search on unsorted input fails silently by returning a wrong "none". An O(n) check keeps the overall bound linear:
def checked_pair_sum(nums: List[int], target: int) -> Optional[Tuple[int, int]]:
"""Pair sum that refuses unsorted input instead of silently failing."""
if not isinstance(nums, list):
raise TypeError("nums must be a list")
if any(nums[k] > nums[k + 1] for k in range(len(nums) - 1)): # O(n) check
raise ValueError("pair search with converging pointers requires sorted input")
lo, hi = 0, len(nums) - 1
while lo < hi:
s = nums[lo] + nums[hi]
if s == target:
return lo, hi
if s < target:
lo += 1
else:
hi -= 1
return None
I.8 Built-in Python alternatives
| Task | Built-in | Cost | Notes |
|---|---|---|---|
| Reverse a list | a.reverse() / a[::-1] / reversed(a) | O(n) | reverse() is in place; the slice copies; reversed is a lazy iterator [20] |
| Palindrome | t == t[::-1] after filtering | O(n) time, O(n) space | simple and fast in CPython; not O(1) space |
| Merge sorted iterables | heapq.merge(*its) | O(N log k) | lazy iterator over k inputs, does not load everything into memory [21] |
| De-duplicate (sorted) | [k for k, _ in itertools.groupby(a)] | O(n) | new list; dict.fromkeys(a) keeps first-seen order for unsorted input |
| Pair sum (unsorted) | dict of value → index | O(n) average | keeps original indices (LeetCode 1) |
| Partner lookup | bisect.bisect_left | O(log n) per query | binary search alternative [24] |
| Sort before pointers | sorted() / list.sort() | O(n log n) | stable; Timsort exploits existing order [19] |
I.9 Comparison of implementations (pair sum)
| Implementation | Time | Extra space | Needs sorted? | Returns original indices? |
|---|---|---|---|---|
| Nested loops | Θ(n²) | O(1) | no | yes |
| Hash map, one pass | O(n) average | O(n) | no | yes |
| Sort + binary search | O(n log n) | O(n) (sort) | sorts | only with an index-carrying sort |
| Sort + two pointers | O(n log n) | O(n) (sort) | sorts | only with an index-carrying sort |
| Two pointers on already-sorted input | Θ(n) worst | O(1) | yes (given) | yes |
JReal-world applications
Two pointers show up wherever production systems combine or scan sorted data in one pass with bounded memory. The examples below are documented uses. Nothing here is a hypothetical "could be used for".
| Domain | Where two pointers appear | Family | Source |
|---|---|---|---|
| Search engines | Boolean AND queries intersect docID-sorted postings lists in O(x+y). | two sequences | [16] |
| Databases | PostgreSQL's merge join sorts both relations on the join key and scans them in parallel, combining matching rows. Each relation is scanned only once. | two sequences | [15] |
| Sorting libraries / backend sorting | Mergesort's merge step; quicksort's partition (i and j scanning inward until they cross); 3-way partitioning for many duplicate keys. | two sequences / converging / partition | [4][6] |
| Large-scale data / external sorting | Merging sorted runs (files, log segments) with a cursor per run; Python exposes this as heapq.merge, a lazy iterator over sorted inputs. | two (k) sequences | [21] |
| Random-number generators, cryptanalysis, number theory | Floyd's cycle detection finds the period of pseudorandom generators and is used in Pollard's rho factorisation and in collision searches on hash functions, all with O(1) memory. | fast / slow | [12][13] |
| Memory-safety tooling / program analysis | Detecting cyclic linked structures (shape analysis) and infinite loops with tortoise and hare. | fast / slow | [12] |
| Web applications / text processing | Validation such as palindromes and mirrored identifiers, in-place compaction of buffers (remove characters or zeros without reallocating), and diffing two sorted ID lists (who was added or removed between two snapshots). | converging / reader-writer / two sequences | Illustration |
KComparison with alternatives
| Technique | Typical time | Space | Requires | Choose it when… | Avoid it when… |
|---|---|---|---|---|---|
| Two pointers (converging) | O(n) (+ sort) | O(1) | sorted order / monotone predicate | pairs in sorted data; mirrored comparisons; memory is tight | you must return original indices of unsorted data |
| Hash map / set | O(n) average | O(n) | hashable keys | unsorted pair sum with indices (LeetCode 1); counting complements | memory is tight; adversarial keys; need sorted output |
| Binary search | O(n log n) total | O(1) | sorted, random access | few queries against a fixed sorted array; partner lookup with extra conditions | a linear scan suffices (pair sum) |
| Sliding window (same-direction pair) | O(n) | O(1)–O(k) | window validity is monotone (e.g. all values ≥ 0) | longest / shortest contiguous segment with a constraint | negative numbers break monotonicity |
| Prefix sums + hash | O(n) | O(n) | additive quantity | subarray sum = k with negatives | you need O(1) space |
| Brute force | O(n²) / O(n³) | O(1) | nothing | n ≤ ~10³, or as a test oracle | production inputs |
Choosing between sort + two pointers and hashing
For 3Sum, Sedgewick and Wayne's ThreeSumFast sorts and then binary-searches for the third value, which costs n² log n [8]. Replacing the binary search with a two-pointer scan gives O(n²) [9][2]. A hash-set approach is also O(n²) but needs O(n) memory and makes de-duplicating triplets awkward. Sorting groups equal values together, so duplicates are skipped by comparing neighbours. Rule of thumb: if the output is about values and sorting is allowed, sort + two pointers. If it is about original positions in unsorted data, hashing.
When two pointers is the wrong tool
- The data is unsorted and you are not allowed to reorder it or lose index information.
- The predicate is not monotone. Moving a pointer must never be able to make a discarded position useful again. Sliding-window sums break with negative numbers for exactly this reason.
- The structure only supports forward traversal (a singly linked list or a stream). Converging pointers need access from both ends, though same-direction variants still work.
- Many queries against the same data, where precomputation (prefix sums, a sorted index plus binary search) pays off.
LCommon mistakes and misconceptions
1. Running converging pointers on unsorted data
nums = [3, 1, 4, 2] # NOT sorted
pair_sum_sorted(nums, 6) # returns None — but 4 + 2 = 6!
The elimination argument "A[lo] is too small for everyone" is only true if A[hi] is the largest value.a = sorted(nums) # values only
pair_sum_sorted(a, 6) # (1, 3): a[1]+a[3]=2+4
# need original indices? use a dict instead
Sort first, or switch to hashing when indices matter.2. lo <= hi instead of lo < hi (pairing an element with itself)
while lo <= hi: # lo == hi allowed
...
pair([1, 5, 9], 10) # may return (1, 1): 5 + 5while lo < hi: # two distinct indices
...
Use <= only when a single element is a legal case (boats in LC 881, DNF's i <= gt).3. Forgetting to move a pointer (infinite loop)
while lo < hi:
if not s[lo].isalnum(): lo += 1
if not s[hi].isalnum(): hi -= 1
if s[lo] == s[hi]: lo += 1; hi -= 1
# mismatch? nothing moves -> loops forever
# and lo can pass hi between the checkswhile lo < hi:
if not s[lo].isalnum(): lo += 1
elif not s[hi].isalnum(): hi -= 1
elif s[lo].lower() != s[hi].lower(): return False
else: lo += 1; hi -= 1
Each branch either moves a pointer or returns, so the variant always shrinks.4. Advancing i after swapping with gt (Dutch flag)
elif nums[i] == 2:
nums[i], nums[gt] = nums[gt], nums[i]
gt -= 1; i += 1 # skips the swapped-in value!
# [1, 2, 0] -> [1, 0, 2] (wrong: 0 never examined)elif nums[i] == 2:
nums[i], nums[gt] = nums[gt], nums[i]
gt -= 1 # i stays: re-examine
The value coming from gt lies in the unknown zone, so it has not been classified yet.5. Missing duplicate skips (3Sum returns repeated triplets)
Without if i > 0 and a[i] == a[i-1]: continue, input [-1, -1, 0, 1, 2] reports [-1, 0, 1] twice. Without the inner skip, [-2, 0, 0, 2, 2] reports [-2, 0, 2] twice. Run both inputs in Lab 7 and watch the red "skip" frames.
6. Complexity misconceptions
- "Two pointers is always O(n)." Only the pointer phase is. With a sort it is O(n log n), and 3Sum is O(n²) because the pointer phase runs n times [9].
- "A
whileinside aformeans O(n²)." Not for monotone pointers: the inner pointer's moves are counted over the whole run, not per outer iteration [2]. - "Slicing is free."
s[lo:hi+1] == s[lo:hi+1][::-1]in a loop copies O(n) characters every time [18].
7. Boundary errors in reader/writer
Starting write at 0 instead of 1 in remove_duplicates compares with nums[-1], the last element in Python, which is a silent wrong answer rather than an exception. Returning write - 1 instead of write is the other classic off-by-one. Invariant-first thinking prevents both: "nums[:write] is the answer so far" pins down both the initial value and the return value.
8. Interview mistakes
- Jumping to code without stating why a pointer may move. Interviewers look for the elimination argument (Section G).
- Not asking whether the input is sorted, whether values repeat, whether indices or values should be returned, and whether the input may be mutated.
- Sorting when the problem needs original indices (LeetCode 1), or using a hash map when O(1) space was requested (LeetCode 167).
- Not testing the empty input, a single element, all-equal values and the no-answer case.
MInterview preparation
Recognising the pattern
| Signal in the statement | Likely pattern |
|---|---|
| "sorted array", "pair / triplet", "target sum", "closest sum" | converging (anchor + converging for k-sum) |
| "in place", "O(1) extra space", "remove / move / compact" | reader / writer |
| "palindrome", "reverse", "mirror", "both ends" | converging on a string |
| "two sorted arrays / lists", "merge", "intersection", "subsequence" | two sequences |
| "three categories", "partition around a pivot" | Dutch national flag |
| "linked list cycle", "duplicate in 1..n without modifying", "middle of list" | fast / slow |
| "longest / shortest subarray / substring such that…" | sliding window (same-direction variant, see the Sliding Window chapter) |
Quick check: which pattern?
nums2 into nums1 (which has spare slots at the end), both sorted.Practice problems (with hints, then solutions)
| Problem | Level | Pattern | Target complexity |
|---|---|---|---|
| 125. Valid Palindrome | Easy | converging on string | O(n), O(1) |
| 977. Squares of a Sorted Array | Easy | converging, fill from back | O(n) |
| 88. Merge Sorted Array | Easy | two sequences, backwards | O(m+n), O(1) |
| 26. Remove Duplicates · 283. Move Zeroes | Easy | reader / writer | O(n), O(1) |
| 167. Two Sum II | Medium | converging | O(n), O(1) |
| 15. 3Sum · 16. 3Sum Closest | Medium | anchor + converging | O(n²) |
| 11. Container With Most Water | Medium | converging, greedy | O(n), O(1) |
| 75. Sort Colors | Medium | three pointers | O(n) one pass, O(1) |
| 287. Find the Duplicate Number | Medium | fast / slow (Floyd) | O(n), O(1), read-only |
| 42. Trapping Rain Water | Hard | converging with running maxima | O(n), O(1) |
Easy — 977. Squares of a Sorted Array
Hint 1
The largest square is at one of the two ends (most negative or most positive).Hint 2
Fill the output from the last index backwards with the larger of the two end squares.Solution
def sorted_squares(nums: List[int]) -> List[int]:
"""LeetCode 977: squares of a sorted array, in sorted order. O(n)."""
n = len(nums)
out = [0] * n
lo, hi = 0, n - 1
for k in range(n - 1, -1, -1): # fill from the back with the larger square
if abs(nums[lo]) > abs(nums[hi]):
out[k] = nums[lo] * nums[lo]
lo += 1
else:
out[k] = nums[hi] * nums[hi]
hi -= 1
return out
Each iteration places one value and moves one pointer: Θ(n) time, plus O(n) for the output. Squaring first and then sorting costs O(n log n).
Easy — 88. Merge Sorted Array (in place)
Hint
Merging from the front would overwrite unread values ofnums1. The free space is at the back.Solution
def merge_into(nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""LeetCode 88: nums1 has length m+n (last n slots are padding).
Fill from the BACK so nothing unread is overwritten. O(m+n), O(1)."""
i, j, k = m - 1, n - 1, m + n - 1
while j >= 0: # once nums2 is used up, nums1's rest is in place
if i >= 0 and nums1[i] > nums2[j]:
nums1[k] = nums1[i]; i -= 1
else:
nums1[k] = nums2[j]; j -= 1
k -= 1
The loop runs while nums2 has elements left. Once it is empty, the rest of nums1 is already in place. O(m+n) time, O(1) space.
Medium — 16. 3Sum Closest
Hint
It is the same skeleton as 3Sum. Instead of collecting exact hits, track the sum with the smallest|s − target|, and move pointers by comparing s with target.Solution
def three_sum_closest(nums: List[int], target: int) -> int:
"""LeetCode 16. O(n^2)."""
a = sorted(nums)
best = a[0] + a[1] + a[2]
for i in range(len(a) - 2):
lo, hi = i + 1, len(a) - 1
while lo < hi:
s = a[i] + a[lo] + a[hi]
if abs(s - target) < abs(best - target):
best = s
if s < target:
lo += 1
elif s > target:
hi -= 1
else:
return s # cannot get closer than exact
return best
O(n²) time and O(1) extra space besides the sort. Why is moving safe? If s < target, any smaller hi gives an even smaller sum, which is farther from target, so lo must increase. This is G.1's argument again.
Hard — 42. Trapping Rain Water
Hint 1
Water above bark is min(maxLeft(k), maxRight(k)) − h[k].Hint 2
Ifh[lo] < h[hi], then some bar on the right is at least as tall as anything we need, so the water at lo depends only on left_max.Solution
def trap(height: List[int]) -> int:
"""LeetCode 42, Trapping Rain Water. O(n) time, O(1) space."""
lo, hi = 0, len(height) - 1
left_max = right_max = 0
water = 0
while lo < hi:
if height[lo] < height[hi]:
left_max = max(left_max, height[lo])
water += left_max - height[lo]
lo += 1
else:
right_max = max(right_max, height[hi])
water += right_max - height[hi]
hi -= 1
return water
Correctness: the water above bar lo is min(maxLeft, maxRight) − height[lo]. Claim: whenever we process lo, left_max ≤ maxRight, so the minimum is left_max. Why: left_max is the height of some bar p ≤ lo. When lo stood at p, we chose to process the left side, so height[p] < height[hi′] for the hi′ of that moment. Since hi only moves left, hi′ is still on the right of the current lo, which gives maxRight ≥ height[p] = left_max. The right side is symmetric. O(n) time and O(1) space, versus O(n) space for the two-prefix-array method. Verified against the definition on 3,000 random inputs in the module.
★Practice problems
Before coding, decide which family the problem belongs to: converging, reader/writer, two sequences or partition. There are 9 problems, grouped by level and topic: 5 easy and 4 medium. Each link opens the problem on the platform where you can submit and test your solution. Tick a problem when you have solved it, and use “My solution” to save your code, approach, complexity and notes to revise later.
Basic5 problems
Direct applications of this chapter’s core idea.
Two Pointers
Two indices moving in one direction each to replace a nested loop.
Intermediate4 problems
The pattern combined with one more idea, or applied to a less obvious setup.
Two Pointers
Two indices moving in one direction each to replace a nested loop.
NAdvanced concepts
N.1 From 2-sum to k-sum
Fixing anchors and recursing turns k-sum into O(nk−1) time with two pointers at the bottom level (4Sum, LeetCode 18, is O(n³)). Whether 3SUM can be solved substantially faster than quadratic was a famous question. Gajentaan and Overmars (1995) defined 3SUM-hardness: a subquadratic algorithm for such a problem would give one for 3SUM, and many computational-geometry problems turn out to be 3SUM-hard [9]. The conjecture that 3SUM needs about n² time was refuted in 2014, when Grønlund and Pettie gave a slightly subquadratic algorithm [9]. Laaksonen's handbook notes the same 2014 result [2]. The gains are only logarithmic-factor improvements, so in practice the sort + two-pointer O(n²) algorithm remains the standard.
N.2 Monotone predicates: the bridge to sliding windows
Same-direction pointers [l, r] generalise to: "for each r, find the smallest l such that the window is valid". This is linear whenever validity is monotone: if [l, r] is valid, so is every [l′, r] with l′ ≥ l. Laaksonen's subarray-sum example and the USACO Books problem are of this form [2][1], and Purdue's slides point out that the sliding window applies when the window's validity is monotone [3]. The Sliding Window chapter develops this family in full. Here it is enough to see that it is the same monotone-pointer argument as G.2.
N.3 Partitioning: Hoare, Lomuto, 3-way and dual-pivot
Quicksort's partition is a converging two-pointer loop. Princeton's version scans i right while a[i] < v and j left while a[j] > v, swaps, and stops when they cross. Stopping on keys equal to the pivot is crucial to avoid quadratic time on inputs with many duplicates [4]. Dijkstra's 3-way partition (Lab 6, generalised to any pivot v) makes quicksort entropy-optimal on inputs with many repeated keys [4][5]. Princeton's demos also show Bentley–McIlroy 3-way partitioning and dual-pivot partitioning, the latter with yet more pointers [5]. CLRS presents the single-pointer Lomuto-style PARTITION alongside mergesort's two-pointer MERGE [22].
N.4 Cycle detection beyond linked lists
Floyd's method works for any iterated function on a finite set, not only for linked lists. That is why it can measure the period of a pseudorandom generator, as in Princeton's COS 126 assignment on linear congruential generators [13], and why it powers Pollard's rho factorisation [12]. Alternatives such as Brent's algorithm also use O(1) memory but need fewer function evaluations [12].
N.5 Many sequences and external memory
With k sorted inputs, a pointer per input plus a min-heap of the current fronts merges them in O(N log k). This is heapq.merge in Python [21], and it is the core of external mergesort and of merge-join plans in databases [15]. Postings-list intersection is further sped up with skip pointers, extra links that let a cursor jump ahead several entries when the other list's docID is far away [16].
N.6 Two pointers on two-dimensional data
A matrix whose rows and columns are both sorted supports a "staircase" search from the top-right corner. Each comparison discards a full row or column, so it takes O(m + n). It is exactly the converging argument of Figure D.2 applied to an explicit matrix. Illustration (LeetCode 240).
ONotebook-ready summary
Definition
Two indices p, q move monotonically through one or two sequences; each step uses the values under them to prove some positions useless and skip them.⇒ each pointer moves ≤ n times ⇒ O(n) pointer work, O(1) extra space.
Four families
① Converginglo=0, hi=n−1, while lo<hi — sorted pair sum, palindrome, reverse, container, 3Sum (anchor + pair), trapping water② Same direction
read always ++, write ++ when kept — dedupe, move zeros, remove value · fast/slow (Floyd)③ Two sequences
i in A, j in B — merge, intersect, subsequence④ Partition
lt, i, gt — Dutch flag: 0s | 1s | unknown | 2s
Why it is correct (say this in interviews)
sorted ⇒ if A[lo]+A[hi] < T, A[lo] + (anything ≤ A[hi]) < T ⇒ drop loif > T, (anything ≥ A[lo]) + A[hi] > T ⇒ drop hi
Invariant: "any answer lies in [lo..hi]". Variant: hi − lo ↓ by 1 each step.
Complexity
pair sum (sorted) O(n)/O(1) · +sort O(n log n) · 3Sum O(n²)dedupe / move zeros / DNF / container / trap O(n)/O(1)
merge Θ(m+n) · Floyd O(μ+λ) time, O(1) space
Sketch it
Python skeletons
lo, hi = 0, len(a)-1while lo < hi: s = a[lo]+a[hi]; ... lo += 1 / hi -= 1w = 1; for r in range(1,n): if a[r]!=a[w-1]: a[w]=a[r]; w+=1slow=fast=start; slow=f(slow); fast=f(f(fast))
Gotchas
✗ unsorted input · ✗<= pairs an item with itself · ✗ a branch that moves nothing ⇒ infinite loop · ✗ DNF: don't i++ after swap with gt · ✗ 3Sum: skip dup anchors AND dup seconds · ✗ slices inside loops are O(n)
Applications
search engines (postings ∩) · DB merge join · mergesort / quicksort partition · k-way merge of sorted files · PRNG period, Pollard rho (Floyd)Pick the tool
sorted pair → 2 pointers · unsorted + indices → hash map · contiguous + all ≥ 0 → sliding window · contiguous + negatives → prefix sums + hashPKnowledge assessment
Try everything here before opening the answer section.
Conceptual questions
- State the loop invariant for converging pair-sum and explain which property of the input it depends on.
- Why is the reader/writer loop O(n) even though
writedoes not advance on every iteration? - In Container With Most Water, why is it wrong to move the taller wall?
- Give two reasons why a hash map might be preferred over sort + two pointers for pair sum, and one reason for the opposite choice.
- In Floyd's algorithm, why does phase 2 restart one pointer at the beginning and move both at speed 1?
Dry-run exercises
- Trace
pair_sum_sorted([-3, -1, 0, 2, 4, 7], 3): list (lo, hi, sum, action) for every iteration. - Trace
sort_colors([1, 2, 0, 2, 0]): show the array and (lt, i, gt) after every iteration. - Trace
max_area([2, 3, 4, 5, 18, 17, 6]): list every (lo, hi, area) and the final best.
Coding problems
- Count pairs below target (LeetCode 2824): return the number of index pairs i < j with nums[i] + nums[j] < target in O(n log n).
- Backspace string compare (LeetCode 844):
'#'deletes the previous character; decide if two strings are equal after typing, using O(1) extra space. - Boats to save people (LeetCode 881): each boat carries at most two people with total weight ≤
limit; return the minimum number of boats.
Practical engineering scenario
Two services each export a sorted stream of user IDs (tens of millions of lines each, too large to load into memory together). You need the sorted list of distinct IDs that appear in either export, streamed to a file. Design the algorithm, give its time and memory cost, and implement the core as a Python generator. What changes if there are 50 exports instead of 2?
Answers
Conceptual 1 — invariant
"If a valid pair exists, one lies entirely within [lo..hi]." It depends on the array being sorted. That is what makes A[lo] + A[hi] < T imply A[lo] + A[k] < T for all k ≤ hi, so lo can be discarded (symmetrically for hi). See G.1.
Conceptual 2 — reader/writer bound
The loop is driven by read, which advances exactly once per iteration, so there are n iterations, each O(1). write only increases and never exceeds read, so its total moves are also ≤ n. That is the aggregate (monotone-pointer) argument of G.2 [2].
Conceptual 3 — taller wall
The area is capped by the shorter wall. Discarding a wall is only safe if every unevaluated pair that uses it is provably no better (G.3). That proof works for the shorter wall: any narrower container keeping it has height ≤ the short wall and smaller width. For the taller wall it fails, because pairs that keep the taller wall but drop the short one can be taller. Smallest counterexample: [1, 3, 3]. Both rules first evaluate (0, 2) = 2 × 1 = 2. "Move the taller wall" then sets hi = 1, evaluates (0, 1) = 1, and stops with 2. The optimum is (1, 2) = 1 × 3 = 3. Moving the shorter wall goes to (1, 2) and finds 3. (Found by brute-force search over random inputs; verify it in Lab 4.)
Conceptual 4 — hash map vs two pointers
Prefer hashing when (a) the input is unsorted and you must return original indices (sorting destroys them unless you sort index pairs), or (b) the data arrives as a stream and you want a single pass without sorting. Prefer two pointers when the input is already sorted or memory is tight: O(1) extra space and worst-case (not just expected) O(n) [18].
Conceptual 5 — Floyd phase 2
At the meeting point, the tortoise has walked μ + a steps, which is a multiple of λ. So μ further steps from the meeting point land on the cycle entrance. A pointer starting at x₀ also reaches the entrance after exactly μ steps. Moving both at speed 1, they first coincide at the entrance [12].
Dry run 1 — pair sum with negatives
| lo | hi | sum | action |
|---|---|---|---|
| 0 | 5 | −3 + 7 = 4 | > 3 → hi = 4 |
| 0 | 4 | −3 + 4 = 1 | < 3 → lo = 1 |
| 1 | 4 | −1 + 4 = 3 | found (1, 4) |
Dry run 2 — Dutch flag on [1, 2, 0, 2, 0]
| before (lt, i, gt) | A[i] | action | array after | after (lt, i, gt) |
|---|---|---|---|---|
| (0, 0, 4) | 1 | i += 1 | [1, 2, 0, 2, 0] | (0, 1, 4) |
| (0, 1, 4) | 2 | swap A[1]↔A[4], gt −= 1 | [1, 0, 0, 2, 2] | (0, 1, 3) |
| (0, 1, 3) | 0 | swap A[1]↔A[0], lt++, i++ | [0, 1, 0, 2, 2] | (1, 2, 3) |
| (1, 2, 3) | 0 | swap A[2]↔A[1], lt++, i++ | [0, 0, 1, 2, 2] | (2, 3, 3) |
| (2, 3, 3) | 2 | swap A[3]↔A[3], gt −= 1 | [0, 0, 1, 2, 2] | (2, 3, 2) |
Now i = 3 > gt = 2, so the loop stops. Result [0, 0, 1, 2, 2] after 4 swaps (one of them a self-swap). You can check this in Lab 6.
Dry run 3 — container [2, 3, 4, 5, 18, 17, 6]
| lo | hi | area | move |
|---|---|---|---|
| 0 | 6 | 6 × min(2,6) = 12 | lo (2 < 6) |
| 1 | 6 | 5 × 3 = 15 | lo |
| 2 | 6 | 4 × 4 = 16 | lo |
| 3 | 6 | 3 × 5 = 15 | lo |
| 4 | 6 | 2 × 6 = 12 | hi (18 ≥ 6) |
| 4 | 5 | 1 × 17 = 17 | hi |
Best = 17 (walls 4 and 5). Notice that the narrowest container wins here because both walls are tall.
Coding 1 — count pairs below target
def count_pairs_less(nums: List[int], target: int) -> int:
"""LeetCode 2824: number of pairs i<j with nums[i]+nums[j] < target.
Sorting does not change the answer (pairs are unordered). O(n log n)."""
a = sorted(nums)
lo, hi = 0, len(a) - 1
count = 0
while lo < hi:
if a[lo] + a[hi] < target:
count += hi - lo # a[lo] works with EVERY partner in lo+1..hi
lo += 1
else:
hi -= 1
return count
Key step: if a[lo] + a[hi] < target, then a[lo] works with every index in lo+1..hi (they are all ≤ a[hi]), so add hi − lo at once. Sorting is allowed because the answer counts unordered pairs. O(n log n) time and O(1) extra space beyond the sort. Verified against brute force on 3,000 random inputs.
Coding 2 — backspace compare in O(1) space
def backspace_compare(s: str, t: str) -> bool:
"""LeetCode 844 in O(1) space: walk both strings from the END,
skipping characters erased by '#'."""
def next_valid(x: str, k: int) -> int:
skip = 0
while k >= 0:
if x[k] == '#':
skip += 1
elif skip:
skip -= 1
else:
return k
k -= 1
return -1
i, j = len(s) - 1, len(t) - 1
while True:
i, j = next_valid(s, i), next_valid(t, j)
if i < 0 or j < 0:
return i < 0 and j < 0
if s[i] != t[j]:
return False
i -= 1; j -= 1
Walking backwards lets us know whether a character survives: we count pending #s and skip that many characters. Each index is visited once, so it is O(|s| + |t|) time and O(1) space. Verified against a stack-based simulation.
Coding 3 — boats to save people
def num_rescue_boats(people: List[int], limit: int) -> int:
"""LeetCode 881: each boat holds at most 2 people and weight <= limit."""
a = sorted(people)
lo, hi = 0, len(a) - 1
boats = 0
while lo <= hi: # '<=': a single remaining person still needs a boat
if a[lo] + a[hi] <= limit:
lo += 1 # lightest rides with heaviest
hi -= 1 # heaviest always leaves
boats += 1
return boats
Greedy and converging: the heaviest person always leaves on this boat. If the lightest person also fits, they ride together, because pairing the heaviest with anyone else could only leave a heavier person behind. Note lo <= hi: a single remaining person still needs a boat. O(n log n). Verified against an exhaustive optimum on small random inputs.
Engineering scenario — streaming merge with de-duplication
Design. Open both exports as line iterators, so only the current line of each is in memory. Keep one cursor per stream and repeatedly emit the smaller current ID, advancing that cursor. Skip an ID equal to the last one emitted, which removes duplicates both within and across streams, since equal IDs are adjacent in the merged order. This is the two-sequence merge of I.5 plus a "last written" check, the reader/writer idea applied to a stream.
def merge_unique(a: Iterable[int], b: Iterable[int]) -> Iterator[int]:
"""Engineering scenario: stream-merge two sorted inputs of any size,
yielding each distinct value once. O(1) memory beyond two cursors."""
ia, ib = iter(a), iter(b)
sentinel = object()
x, y = next(ia, sentinel), next(ib, sentinel)
last = sentinel
while x is not sentinel or y is not sentinel:
if y is sentinel or (x is not sentinel and x <= y):
v, x = x, next(ia, sentinel)
else:
v, y = y, next(ib, sentinel)
if v != last:
yield v
last = v
Cost. Time Θ(N₁ + N₂) comparisons and O(1) memory (two current values plus the last emitted). The work is I/O-bound. Use buffered file reading and write output in chunks.
50 exports. Comparing 50 fronts each step costs O(k), so use a min-heap of the fronts: heapq.merge(*streams) gives O(N log k) time and O(k) memory [21]. Then de-duplicate with the same "skip if equal to last" filter, for example (k for k, _ in itertools.groupby(heapq.merge(*streams))). This is the same plan databases use for merge joins and external sorts [15].
QReferences and further reading
- "Two Pointers" (Silver module) — USACO Guide, Competitive Programming Initiative. Definition; opposite-ends and same-direction variants; O(N) argument for both pointers moving ≤ N times; Sum of Two Values. Supports B, C, G.2, N.2.
- Competitive Programmer's Handbook, Ch. 8.1 "Two pointers method" — Antti Laaksonen (University of Helsinki); full book PDF at cses.fi/book/book.pdf. Monotone-pointer (amortized) analysis, subarray sum, 2SUM in O(n log n) with sorting, binary-search alternative, 3SUM in O(n²) and the 2014 subquadratic result. Supports B, C, G.2, H, K, N.1.
- "Topic 2: Two Pointers and Sliding Window" — Ninghui Li, Purdue University, Competitive Programming I (Fall 2019). Definition; Two Sum II linear-time argument; Container With Most Water insight; monotone sliding windows. Supports B, C, G.3, N.2.
- "2.3 Quicksort" — Robert Sedgewick & Kevin Wayne, Algorithms, 4th ed., Princeton University. Partitioning with i/j pointers that cross; stopping on equal keys; Dijkstra 3-way partition invariant; entropy-optimality. Supports B, G.4, J, N.3.
- "2.3 Partitioning Demos" — Sedgewick & Wayne, Princeton COS 226 (Spring 2014). Step-by-step Sedgewick 2-way, Dijkstra 3-way, Bentley–McIlroy and dual-pivot partitioning. Supports B, G.4, N.3.
- "2.2 Mergesort" lecture slides — Sedgewick & Wayne, Princeton COS 226 (Spring 2023). Merging two sorted halves; best case n/2 and worst case n−1 compares. Supports B, H, J.
- CompSci 220 Lecture 9: Mergesort — linear-time merge — University of Auckland. Θ(n) merge with indices i, j, k; Θ(n log n) mergesort. Supports B, H.
- ThreeSumFast.java — Sedgewick & Wayne, Algorithms, 4th ed. §1.4. Sort + binary search 3-sum with n² log n running time (the baseline that two pointers improves). Supports K.
- "3SUM" — Wikipedia (with primary references to Gajentaan & Overmars 1995 and Grønlund & Pettie 2014). Quadratic sort-and-scan algorithm; 3SUM-hardness; refutation of the quadratic conjecture. Supports H, K, L, N.1.
- "Dutch national flag problem" — Wikipedia. Problem proposed by Dijkstra; relation to 3-way quicksort partitioning; Θ(n) moves and examinations. Supports B, G.4, H.
- "Dutch National Flag" — Lloyd Allison, Monash University. Dijkstra's use of the problem as a program-derivation and proof exercise; two- and three-colour invariants. Supports B.
- "Cycle detection" — Wikipedia (citing Knuth, TAOCP Vol. 2). Floyd's tortoise and hare; attribution to Floyd via Knuth (disputed); O(λ+μ) time, O(1) space; the μ-finding phase; applications (PRNGs, Pollard rho, cryptanalysis, linked-list shape analysis); Brent's algorithm. Supports B, G.5, H, J, N.4.
- COS 126 Assignment: Linear congruential generator — Floyd's algorithm — Princeton University (Fall 2001). Floyd's two-phase method applied to finding the period of an LCG. Supports B, J, N.4.
- CSCE 411 slides: "The Hare and the Tortoise" — Andreas Klappenecker, Texas A&M University (Spring 2017). Proof that the pointers meet at a multiple of the cycle length, within s + L steps. Supports G.5, H.
- "Planner/Optimizer" (merge join) — PostgreSQL Global Development Group, PostgreSQL Documentation. Merge join sorts both relations on the join key and scans them in parallel, each scanned once. Supports J, N.5, P.
- "Processing Boolean queries" (§1.3) — C. D. Manning, P. Raghavan & H. Schütze, Introduction to Information Retrieval, Cambridge University Press / Stanford NLP. Postings-list intersection with two pointers in O(x + y); requirement of a global docID order. Supports H, J, N.5.
- EWD 608: "An elephant inspired by the Dutch National Flag" — Edsger W. Dijkstra, E. W. Dijkstra Archive, University of Texas at Austin. Primary-source manuscript by Dijkstra on the problem (further reading for B and G.4).
- "TimeComplexity" — Python Wiki (python.org). CPython costs: list indexing O(1), slicing O(k),
x in listO(n),pop(0)/insert(0)O(n), dict/set average O(1) and worst O(n). Supports C, F, H, L, P. - "Sorting Techniques" — Python Software Foundation, Python 3 Documentation.
sorted()vslist.sort(); guaranteed stability; Timsort exploits existing order. Supports H, I.8. - "Built-in Types" — Python Software Foundation, Python 3 Documentation. Immutability of
str;str.isalnum,str.lower/casefold;list.reverse; sequence slicing. Supports F, I. - "heapq — Heap queue algorithm" — Python Software Foundation, Python 3 Documentation.
heapq.merge: lazily merges multiple sorted inputs into one sorted iterator. Supports I.8, J, N.5, P. - Introduction to Algorithms, 4th ed. — T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein (CLRS), MIT Press, 2022. Standard treatment of MERGE (mergesort) and PARTITION (quicksort), loop invariants. Supports N.3.
- LeetCode problem set — original statements linked in Sections C, D, I, M, N and P (problems 11, 15, 16, 18, 26, 27, 42, 75, 88, 125, 167, 240, 283, 287, 844, 881, 977, 2824). Problem contracts (e.g. 1-based indices in 167, in-place length return in 26).
- "bisect — Array bisection algorithm" — Python Software Foundation, Python 3 Documentation. Binary search on sorted lists (the O(log n)-per-lookup alternative). Supports I.8.
- "How are lists implemented in CPython?" (Design and History FAQ) — Python Software Foundation, Python 3 Documentation. Lists are variable-length arrays of references; indexing cost is independent of the index and list size. Supports F.
DSA Learning Studio · Chapter: Two Pointers (Arrays & Strings) · All Python code executed and verified; all labs run entirely in your browser.