TechniqueTechniqueA reusable problem-solving pattern you apply on top of data structures to turn slow solutions into fast ones.e.g. Two pointers, sliding window, prefix sums
DSA Learning Studio · Algorithmic Patterns on Arrays & Strings

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.

Difficulty: Beginner → Intermediate (Section N: Advanced) Reading time: ~75 minutes (+ 40 min labs & exercises) Language: Python 3.8+ Builds on: Arrays · Time & Space Complexity · Prefix Sum

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:

  1. Define the two-pointer technique precisely and name its four families: converging, same-direction (reader/writer, fast/slow), two-sequence and partition.
  2. Explain why a pointer may be moved — the elimination argument — and prove correctness with a loop invariant.
  3. Prove the O(n) bound with the "each pointer only moves one way" (potential-function) argument.
  4. 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.
  5. Choose between two pointers, hashing, binary search, sliding windows and prefix sums, and recognise when two pointers is the wrong tool.
  6. Avoid the classic bugs: off-by-one loop conditions, infinite loops, missing duplicate skips and running converging pointers on unsorted data.
The one-sentence promise When the data has order (sorted values, or positions you scan left-to-right), one comparison can rule out a whole row of candidate answers. Two indices that each move in one direction then do the work of a nested loop in a single pass. [1][2]
How the visuals in this chapter are made This environment has no image-generation model, so every "whiteboard" illustration is drawn in code as SVG, with marker-style strokes and handwriting labels. The figures that contain data (traces, matrices, charts) are produced by running the real algorithm, so every number shown is correct. All eight labs in Section E work: each one records every state of the algorithm so you can play, pause, step forward and backward, and edit the input. Passages tagged Illustration are my own worked examples, not claims taken from a source.

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

Formal definition A two-pointer algorithm over sequences of total length n keeps a state (p, q) of two positions, plus O(1) extra variables. At each step it examines the elements at p and q and advances at least one pointer monotonically: each pointer only ever moves in one fixed direction. Because each pointer can move at most n times, the loop runs O(n) times. Correctness rests on an invariant: every position a pointer has passed over can no longer be part of an answer that has not already been found. Laaksonen's Competitive Programmer's Handbook treats the method as a case of amortized analysis for exactly this reason: both pointers move in one direction only, which keeps the total work linear [2].
Plain-English definition Put one finger on each of two places in a list. Look at what is under your fingers, decide which finger is "stuck" on a hopeless value, and slide that finger along. Never slide a finger backwards. When your fingers meet or fall off the end, you are done. Every slide throws away a possibility you can prove was useless.

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 i from the left and index j from 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)

TermMeaningExample
PointerAn index (or node reference) marking a position.lo = 0
Window / active regionThe positions that may still hold an answer.A[lo..hi]
Monotone movementA pointer only ever moves one way, so it never revisits a position.lo only increases
Elimination stepOne comparison proves that a position cannot be part of any remaining answer, so the pointer leaves it.sum too small ⇒ discard A[lo]
InvariantA statement that is true before every iteration and gives correctness."if a pair exists, it lies in [lo..hi]"
Termination conditionWhen 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].

Problem: PAIR-SUM (sorted) Input: a list A[0..n−1] of integers sorted in non-decreasing order, and a target T.
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

AlternativeTimeExtra spaceLimitation
Brute force, all pairsΘ(n²)O(1)Too slow beyond about 10⁴ elements.
Binary search for T − A[i] for each iO(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 farO(n) expectedO(n)Uses linear memory, expected rather than worst-case O(1) lookups [18], and ignores the sortedness we were given.
Two pointersO(n) worst caseO(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].

Real-world analogy: buying two gifts with an exact budget Lay price tags on a table, cheapest on the left and most expensive on the right. Pick up the cheapest and the most expensive. Too expensive together? The expensive one can't work even with the cheapest item, so put it back. Too cheap? The cheap one can't reach the budget even with the most expensive item, so put it back. Every "put back" is permanent, and you never reconsider a tag. You finish after at most one look per tag. Illustration

DVisual whiteboard explanations

Figure D.1 · Concept introductionThe four families of two pointers
① Converging — start at both ends② Same direction — reader & writer③ Two sequences — one pointer each④ Partition — three pointers1031426384115lohithey move toward each other until they meet00112213242536writereadkept so farboth move right; read ≥ write alwaysA147B238i← jout123next: min(4, 8) = 40001121324051627ltigt0s | 1s | i…gt unknown | 2sone pass, constant extra space
blue: original datayellow/orange: active pointergreen: settled resultpurple: relation / data flowgrey: already consumed
  1. Converging: lo starts at index 0 and hi at n−1. They move toward each other, and the loop ends when they meet.
  2. Same direction: read visits every element, and write marks where the next kept element goes. Everything left of write is final.
  3. Two sequences: i walks list A and j walks list B. The smaller front value goes to the output.
  4. Partition: three indices split the array into four zones (0s, 1s, unknown, 2s) that change in one pass.
Technical interpretation: in every family, each pointer is monotone and bounded by the input length, so the total number of pointer moves is O(n). The families differ only in the rule that decides which pointer moves.

The most important picture in this chapter is the next one. It explains why converging pointers cannot miss a pair.

Figure D.2 · Comparison with the alternativeThe pair-sum matrix: one comparison deletes a whole row or column
hi = j (A[j])lo = i0113243648511103142638411545792121794113141051215141719A = [1, 3, 4, 6, 8, 11], target = 101. 1+11 = 12 > 10 → strike column 52. 1+8 = 9 < 10 → strike row 03. 3+8 = 11 > 10 → strike column 44. 3+6 = 9 < 10 → strike row 15. A[2]+A[3] = 10 = 10 ✔ foundBrute force checks every white+red+yellowcell above the diagonal: 15 pairs.Two pointers visit only 5 cells — eachstep deletes a whole row or column.
cell actually examined (numbered in order)pair eliminated without being examinedanswerpath taken by (lo, hi)invalid (i ≥ j)
Cell (i, j) holds A[i] + A[j]. Because A is sorted, sums increase to the right along a row and downward along a column.
  1. 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.
  2. Move left to (0, 4): 9 < 10. Every other cell in row 0 is ≤ 9, so the whole row 0 is struck.
  3. Steps 3 and 4 strike column 4 and row 1 in the same way. Step 5 lands on 10, the answer.
Technical interpretation: the search is a monotone staircase walk through a sorted matrix. Brute force examines all 15 pairs above the diagonal. Two pointers examine at most n − 1 = 5 cells, because each examined cell deletes an entire row or column. This is why the algorithm is linear and complete.
Figure D.3 · Step-by-step executionThe same search, drawn on the array
Find two values summing to 10 in a sorted arraystep 11031426384115lohi1 + 11 = 12 > 10: 11 too big for anyone → hi −= 1step 21346811lohi1 + 8 = 9 < 10: 1 too small for anyone → lo += 1step 31346811lohi3 + 8 = 11 > 10: 8 too big for anyone → hi −= 1step 41346811lohi3 + 6 = 9 < 10: 3 too small for anyone → lo += 1step 51346811lohi4 + 6 = 10 ✔ return (2, 3)
lo / hi under comparisonstill possibleproven uselessfound
The active window 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.
Figure D.4 · Before-and-after comparisonReader/writer: removing duplicates from a sorted array in place
before00011213142526373849after00112233442526373849write = k = 5the unique values, in orderleftovers (ignored)read visits every cell once; write advances only for a new value
inputcompacted result A[0..k−1]leftover slotscopy performed by A[write] = A[read]
  1. read scans indices 1…9 and compares each value with the last kept value, A[write−1].
  2. A new value (first occurrences at indices 2, 5, 7, 9) is copied to A[write], and write advances.
  3. At the end, write = 5 is the number of distinct values. Positions 5…9 hold leftovers that the caller ignores. This is exactly LeetCode 26's contract [23].
Technical interpretation: invariant "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.

Lab 1 · Converging pointersPair sum in a sorted array + the elimination matrix

Watch each comparison strike out a whole row (lo too small) or column (hi too big) of the pair matrix.

lo–
hi–
sum–
checks0
brute force–
pair matrix (row = lo index, column = hi index)
Press Load.
Lab 2 · Converging pointers on a stringValid palindrome (ignore punctuation and case)

The pointers skip characters that are not letters or digits, then compare lowercase forms, as in LeetCode 125.

Press Load.
Lab 3 · Same-direction pointersReader / writer compaction

One pointer (read) inspects every element; the other (write) marks the end of the answer built so far. Choose a task.

read–
write–
writes0
Press Load.
Lab 4 · Converging pointers with a greedy ruleContainer With Most Water

Area = width × the shorter wall. Always move the shorter wall: keeping it can only produce narrower containers capped by the same height.

lo–
hi–
area–
best–
Press Load.
Lab 5 · Pointers over two sequencesMerge / intersect two sorted lists

Merge copies the smaller front element (a tie takes A first, which keeps the merge stable). Intersect outputs equal values and advances the smaller side otherwise.

A
B
output
Press Load.
Lab 6 · Three pointersDutch National Flag / Sort Colors (0s, 1s, 2s in one pass)

Invariant: [0, lt) = 0 · [lt, i) = 1 · [i, gt] unknown · (gt, n) = 2. Notice that i does not advance after a swap with gt.

lt–
i–
gt–
swaps0
Press Load.
Lab 7 · Anchor + converging pair3Sum: all unique triplets summing to 0

Sort once, fix an anchor i (purple), then run Lab 1's pair search on A[i+1..n−1] for target −A[i]. Duplicate anchors and duplicate second values are skipped.

triplets found:
Press Load.
Lab 8 · Fast / slow pointersFloyd's tortoise & hare: find the duplicate (LC 287)

An array of n+1 values in 1..n defines a successor function i → A[i]. Starting from index 0, the path forms a "ρ": a tail, then a cycle. The duplicate value is the cycle's entrance, because two different indices point to it.

phase–
tortoise–
hare–
steps0
Press Load.

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.

Figure F.1 · Memory representationIndices into a contiguous array of references
Python list objectob_refcnt / ob_typeob_size = 6allocated = 8ob_item ●contiguous array of references (8 slots)●0●1●2●3●4●5671346811int objects live elsewhere on the heaplo = 0hi = 5lo, hi are plain ints (indices).A[lo]: address = base + lo·(ref size)→ O(1) random access by indexstr is immutable: s[lo] reads fine, s[lo] = "x" raises TypeError → convert with list(s) to swap in place
list headerreference slots (data)slots under lo / hireference → objectstring caveat
The list header points to a block of reference slots, with spare capacity shown dashed. 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

Figure F.2 · Internal workingControl flow: every path through the loop shrinks the window
lo = 0, hi = n − 1lo < hi ?noreturn Noneyess = A[lo] + A[hi]compare s, Ts = Treturn (lo, hi)s < Tlo += 1s > Thi −= 1loop: windowshrank by 1
initialisationdecision / pointer movesuccess exitfailure exitloop back-edge
Each iteration takes exactly one of three exits: return the answer, move 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)

  1. Initialise lo = 0, hi = n − 1. The window holds the whole array. For n ≤ 1 the loop never runs and we return None.
  2. Read A[lo] and A[hi]: two O(1) index operations.
  3. 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 compare A[lo] with T − A[hi] instead.
  4. Decide with one three-way comparison against T.
  5. Mutate exactly one pointer, by ±1. Nothing else changes, and the array itself is never modified.
  6. 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

FamilyStateRule per stepStops whenWho moves
Converginglo, hicompare f(A[lo], A[hi]) with goal; drop the side proven uselesslo ≥ hiexactly one (or both on a match)
Reader/writerread, writeread always advances; write advances only when A[read] is keptread = nread every step, write sometimes
Two sequencesi, jadvance the pointer at the smaller front value (merge: and emit it)one list exhaustedone per step (both on a tie in intersection)
Partition (DNF)lt, i, gtclassify A[i]: swap to the left zone, the right zone, or leave iti > gt(lt and i), or gt, or i
Fast/slow (Floyd)slow, fastslow takes one step, fast takes twothey meet or fast reaches the endboth

Edge cases every implementation must handle

CaseWhat happensCorrect behaviour
Empty input / one elementhi = −1 or 0; lo < hi is false at oncereturn "none" without indexing
All elements equale.g. [5,5,5], T = 10first check succeeds; with lo < hi the same element is never used twice
Duplicates (3Sum)equal anchors or second values repeat tripletsskip equal neighbours after sorting (Lab 7)
Negative numberssorted order still holdsconverging pair-sum still works; the sliding window technique for subarray sums does not (Section L)
Unsorted inputthe elimination argument is falsesort first (if the original indices are not required) or use a hash map
Strings with punctuation / Unicodepointers stop on non-lettersskip with str.isalnum() and compare .lower() (or .casefold()) [20]

GMathematical foundation

G.1 Correctness of converging pair-sum (loop invariant)

Invariant I Before every iteration: if some pair (i*, j*) with i* < j* and A[i*] + A[j*] = T exists, then there is one with lo ≤ i* < j* ≤ hi.

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

Figure G.1 · Proof intuitionThe shorter wall caps every container that keeps it
011826324554687387current container (0, 8): area = min(1, 7) × 8 = 8(0,3): area ≤ 1 × 3 = 3 < 8(0,5): area ≤ 1 × 5 = 5 < 8(0,7): area ≤ 1 × 7 = 7 < 8The shorter wall (h = 1) caps EVERY narrower container that keeps itso no pair (0, k) with k < 8 can beat 8: discard index 0 (lo += 1)
current walls lo, hiother walls / current watercandidates ruled out without being evaluatedconclusion
With heights [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].

Figure G.2 · Proof intuitionThe ρ-shaped sequence and the meeting-point algebra
x0x1x2x3x4x5x6x7x8entrance x_μmeettail: μ stepscycle: λslow walked μ + afast walked 2(μ + a)fast is ahead by whole laps:2(μ + a) − (μ + a) = kλ⇒ μ + a = kλ⇒ μ ≡ −a (mod λ)So: walk μ more steps fromthe meeting point and you landexactly on the entrance.Floyd's tortoise & hare on a 'rho' (ρ) shape
tail x₀…xμ−1cycle of length λentrance xμmeeting point
The tortoise has walked μ + a steps when it meets the hare, and the hare has walked twice as far. The difference, μ + a, is a whole number of laps kλ. So μ ≡ −a (mod λ): from the meeting point, μ more steps finish the lap exactly at the entrance. A pointer restarted at x₀ also needs μ steps to get there, so the two arrive together. Technical interpretation: in LeetCode 287, f(i) = A[i]. The entrance has two predecessors (one on the tail, one on the cycle), so its value appears twice in the array. Lab 8 animates this.

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

OperationBestAverageWorstAux. spaceWhy
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) outputbetween min(m,n) and m+n−1 compares [6][7]
Intersect sorted listsΘ(min(m,n))O(m+n)Θ(m+n)Θ(1) + outputeach 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 sortn 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].

Figure H.1 · Time complexity visualizationQuadratic pair checks versus a linear scan
0102030400200400600800brute force: n(n−1)/2two pointers: ≤ n − 1n (array length)pair checks (worst case)measured (Section I)nbrute2-ptr1045≤ 91004,950≤ 991,000499,500≤ 999
brute force n(n−1)/2two pointers ≤ n−1
Worst-case (no solution) pair checks as n grows. The table on the right shows counts measured by the Section I module on arrays with no solution. At n = 1000 brute force performs 499,500 checks and two pointers at most 999, about 500× fewer, and the gap keeps growing linearly with n. Technical interpretation: the ratio (n(n−1)/2)/(n−1) = n/2, so the speed-up itself is Θ(n).

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 += 1 creates 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 and x in list is O(n) [18]. Writing if target - a[i] in a[i+1:] inside a loop silently turns a "two pointer" solution back into O(n²).
  • list.pop(0) and insert(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

Steplohinums[lo]nums[hi]sumDecisionWindow after
10511112> 10 → hi −= 1[0..4]
204189< 10 → lo += 1[1..4]
3143811> 10 → hi −= 1[1..3]
413369< 10 → lo += 1[2..3]
5234610found → (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])

readnums[read]nums[write−1]new?actionwrite after
100noskip1
210yesnums[1] = 12
3, 41, 11noskip2
521yesnums[2] = 23
622noskip3
732yesnums[3] = 34
833noskip4
943yesnums[4] = 45 = 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

TaskBuilt-inCostNotes
Reverse a lista.reverse() / a[::-1] / reversed(a)O(n)reverse() is in place; the slice copies; reversed is a lazy iterator [20]
Palindromet == t[::-1] after filteringO(n) time, O(n) spacesimple and fast in CPython; not O(1) space
Merge sorted iterablesheapq.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 → indexO(n) averagekeeps original indices (LeetCode 1)
Partner lookupbisect.bisect_leftO(log n) per querybinary search alternative [24]
Sort before pointerssorted() / list.sort()O(n log n)stable; Timsort exploits existing order [19]

I.9 Comparison of implementations (pair sum)

ImplementationTimeExtra spaceNeeds sorted?Returns original indices?
Nested loopsΘ(n²)O(1)noyes
Hash map, one passO(n) averageO(n)noyes
Sort + binary searchO(n log n)O(n) (sort)sortsonly with an index-carrying sort
Sort + two pointersO(n log n)O(n) (sort)sortsonly with an index-carrying sort
Two pointers on already-sorted inputΘ(n) worstO(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".

Figure J.1 · Real-world applicationIntersecting postings lists in a search engine
Search engine: AND-query = intersect two sorted postings listsBrutus124113145173174Calpurnia23154101result231equal → output, advance bothsmaller → advance that pointer onlycost: O(x + y) for lists of length x, ySame pattern: sort-merge join in a database (both tables sorted on the key, scanned once in parallel)
postings (sorted docIDs)docIDs in both lists → resultmatch found by the two cursors
This is the textbook example from Manning, Raghavan and Schütze: to answer Brutus AND Calpurnia, walk one pointer through each docID-sorted postings list. On equal IDs, output and advance both. Otherwise advance the smaller. The cost is linear in the total number of postings, O(x + y) [16]. Technical interpretation: this is the "intersect sorted lists" routine of Section I.5. It works only because every postings list is sorted by the same global order (docID) [16].
DomainWhere two pointers appearFamilySource
Search enginesBoolean AND queries intersect docID-sorted postings lists in O(x+y).two sequences[16]
DatabasesPostgreSQL'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 sortingMergesort'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 sortingMerging 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 theoryFloyd'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 analysisDetecting cyclic linked structures (shape analysis) and infinite loops with tortoise and hare.fast / slow[12]
Web applications / text processingValidation 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 sequencesIllustration
Engineering pattern: "sorted + streaming ⇒ two cursors" If two inputs are already sorted on the same key (index order, docID, timestamp), you can combine, diff, join or de-duplicate them in one pass, using memory proportional to the number of cursors rather than the data size. That is why databases sort before joining [15] and search engines keep postings sorted [16]. Section P's engineering scenario builds such a merger.

KComparison with alternatives

Figure K.1 · Comparison with alternative approachesWhich tool fits the question?
What does the problem ask for?Pair / triple witha target sumsorted → convergingunsorted → hash mapContiguoussubarray / substringall ≥ 0 → windownegatives → prefix sumsFilter / compactin placereader / writer3 classes → Dutch flagCombine twosorted sequencesparallel pointersk lists → heap mergeCycle in asuccessor chainfast / slowFloyd: O(1) space
questionshape of the problemrecommended technique
Start from what is asked, not from the technique. Two pointers is the right answer when order (sorted values or a left-to-right scan) makes a pointer's past positions provably useless. Otherwise, hashing, prefix sums or other structures fit better. Technical interpretation: each green box is the cheapest algorithm whose correctness argument matches the problem's structure: monotonicity (two pointers / sliding window), additivity with negatives (prefix sums), or arbitrary equality lookups (hashing).
TechniqueTypical timeSpaceRequiresChoose it when…Avoid it when…
Two pointers (converging)O(n) (+ sort)O(1)sorted order / monotone predicatepairs in sorted data; mirrored comparisons; memory is tightyou must return original indices of unsorted data
Hash map / setO(n) averageO(n)hashable keysunsorted pair sum with indices (LeetCode 1); counting complementsmemory is tight; adversarial keys; need sorted output
Binary searchO(n log n) totalO(1)sorted, random accessfew queries against a fixed sorted array; partner lookup with extra conditionsa 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 constraintnegative numbers break monotonicity
Prefix sums + hashO(n)O(n)additive quantitysubarray sum = k with negativesyou need O(1) space
Brute forceO(n²) / O(n³)O(1)nothingn ≤ ~10³, or as a test oracleproduction 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

✗ Wrong
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.
✓ Right
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)

✗ Wrong
while lo <= hi:   # lo == hi allowed
    ...
pair([1, 5, 9], 10)  # may return (1, 1): 5 + 5
✓ Right
while 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)

✗ Wrong
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 checks
✓ Right
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
Each branch either moves a pointer or returns, so the variant always shrinks.

4. Advancing i after swapping with gt (Dutch flag)

✗ Wrong
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)
✓ Right
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 while inside a for means 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 statementLikely 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?

1. Merge nums2 into nums1 (which has spare slots at the end), both sorted.
2. Find the middle node of a singly linked list in one pass.
3. Remove all occurrences of a value in place and return the new length.
4. Return the squares of a sorted array (which may contain negatives) in sorted order, in O(n).

Practice problems (with hints, then solutions)

ProblemLevelPatternTarget complexity
125. Valid PalindromeEasyconverging on stringO(n), O(1)
977. Squares of a Sorted ArrayEasyconverging, fill from backO(n)
88. Merge Sorted ArrayEasytwo sequences, backwardsO(m+n), O(1)
26. Remove Duplicates · 283. Move ZeroesEasyreader / writerO(n), O(1)
167. Two Sum IIMediumconvergingO(n), O(1)
15. 3Sum · 16. 3Sum ClosestMediumanchor + convergingO(n²)
11. Container With Most WaterMediumconverging, greedyO(n), O(1)
75. Sort ColorsMediumthree pointersO(n) one pass, O(1)
287. Find the Duplicate NumberMediumfast / slow (Floyd)O(n), O(1), read-only
42. Trapping Rain WaterHardconverging with running maximaO(n), O(1)

Easy — 977. Squares of a Sorted Array

Hint 1The largest square is at one of the two ends (most negative or most positive).
Hint 2Fill 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)

HintMerging from the front would overwrite unread values of nums1. 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

HintIt 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 1Water above bar k is min(maxLeft(k), maxRight(k)) − h[k].
Hint 2If h[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.

Level
Difficulty
0 / 9 solved
Saved in this browser

Basic5 problems

Direct applications of this chapter’s core idea.

Two Pointers

Two indices moving in one direction each to replace a nested loop.

  1. Valid Palindrome⤢EASYLeetCode
  2. Squares of a Sorted Array⤢EASYLeetCode
  3. Merge Sorted Array⤢EASYLeetCode
  4. Reverse String⤢EASYLeetCode

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.

  1. Partition Labels⤢MEDIUMLeetCode
  2. String Compression⤢MEDIUMLeetCode
  3. 3 Sum⤢MEDIUMLeetCode
  4. 3 Sum Closest⤢MEDIUMLeetCode

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

① Converging lo=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 lo
if > 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

converging13468sum < T → lo++ · sum > T → hi−−reader / writer01212wrkeep → a[w] = a[r], w++ ; r++ alwaystwo lists147238emit the smaller front, advance it

Python skeletons

lo, hi = 0, len(a)-1
while lo < hi: s = a[lo]+a[hi]; ... lo += 1 / hi -= 1
w = 1; for r in range(1,n): if a[r]!=a[w-1]: a[w]=a[r]; w+=1
slow=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 + hash

PKnowledge assessment

Try everything here before opening the answer section.

Conceptual questions

  1. State the loop invariant for converging pair-sum and explain which property of the input it depends on.
  2. Why is the reader/writer loop O(n) even though write does not advance on every iteration?
  3. In Container With Most Water, why is it wrong to move the taller wall?
  4. Give two reasons why a hash map might be preferred over sort + two pointers for pair sum, and one reason for the opposite choice.
  5. In Floyd's algorithm, why does phase 2 restart one pointer at the beginning and move both at speed 1?

Dry-run exercises

  1. Trace pair_sum_sorted([-3, -1, 0, 2, 4, 7], 3): list (lo, hi, sum, action) for every iteration.
  2. Trace sort_colors([1, 2, 0, 2, 0]): show the array and (lt, i, gt) after every iteration.
  3. Trace max_area([2, 3, 4, 5, 18, 17, 6]): list every (lo, hi, area) and the final best.

Coding problems

  1. 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).
  2. Backspace string compare (LeetCode 844): '#' deletes the previous character; decide if two strings are equal after typing, using O(1) extra space.
  3. 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
lohisumaction
05−3 + 7 = 4> 3 → hi = 4
04−3 + 4 = 1< 3 → lo = 1
14−1 + 4 = 3found (1, 4)
Dry run 2 — Dutch flag on [1, 2, 0, 2, 0]
before (lt, i, gt)A[i]actionarray afterafter (lt, i, gt)
(0, 0, 4)1i += 1[1, 2, 0, 2, 0](0, 1, 4)
(0, 1, 4)2swap A[1]↔A[4], gt −= 1[1, 0, 0, 2, 2](0, 1, 3)
(0, 1, 3)0swap A[1]↔A[0], lt++, i++[0, 1, 0, 2, 2](1, 2, 3)
(1, 2, 3)0swap A[2]↔A[1], lt++, i++[0, 0, 1, 2, 2](2, 3, 3)
(2, 3, 3)2swap 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]
lohiareamove
066 × min(2,6) = 12lo (2 < 6)
165 × 3 = 15lo
264 × 4 = 16lo
363 × 5 = 15lo
462 × 6 = 12hi (18 ≥ 6)
451 × 17 = 17hi

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

  1. "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.
  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.
  3. "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.
  4. "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.
  5. "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.
  6. "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.
  7. 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.
  8. 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.
  9. "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.
  10. "Dutch national flag problem" — Wikipedia. Problem proposed by Dijkstra; relation to 3-way quicksort partitioning; Θ(n) moves and examinations. Supports B, G.4, H.
  11. "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.
  12. "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.
  13. 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.
  14. 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.
  15. "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.
  16. "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.
  17. 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).
  18. "TimeComplexity" — Python Wiki (python.org). CPython costs: list indexing O(1), slicing O(k), x in list O(n), pop(0)/insert(0) O(n), dict/set average O(1) and worst O(n). Supports C, F, H, L, P.
  19. "Sorting Techniques" — Python Software Foundation, Python 3 Documentation. sorted() vs list.sort(); guaranteed stability; Timsort exploits existing order. Supports H, I.8.
  20. "Built-in Types" — Python Software Foundation, Python 3 Documentation. Immutability of str; str.isalnum, str.lower/casefold; list.reverse; sequence slicing. Supports F, I.
  21. "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.
  22. 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.
  23. 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).
  24. "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.
  25. "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.