Skip to content
Tech Interview Prep
Technical interview guide

Two Pointers

Two indices moving through a sequence, from opposite ends or in lockstep, to cut brute-force O(n²) scans to O(n).

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with operation costs cited from CPython 3.14 and the C++ standard containers.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

How does the two-pointer technique achieve O(N) time complexity on sorted inputs compared to O(N^2) brute-force, and what core invariant must hold for it to be applicable?

Answer

The 60-second answer

Two pointers turns an $O(N^2)$ scan of all pairs into a single $O(N)$ pass by exploiting sortedness: each comparison lets you permanently discard one index, so no pair is ever revisited.

The invariant is monotonicity. With left at the low end and right at the high end of a sorted array, moving left right can only increase nums[left] + nums[right], and moving right left can only decrease it. That is what makes discarding safe.

Concretely, for a target sum: if nums[left] + nums[right] < target, then nums[left] is too small to pair with right or anything to its left. Every such pair is also below target. So left is dead; advance it. If the sum is too large, nums[right] is too big for left or anything to its right; retreat right. Each step removes one index from consideration, so the pointers cross after at most $N-1$ steps. Assumptions: the array is sorted ascending, we want one witness pair of distinct indices, and the evaluator (here, addition) is monotone in each pointer.

Trace: nums = [1, 3, 4, 6, 8, 11], target = 10:

leftrightsumaction
0 (1)5 (11)12> 10, retreat right
0 (1)4 (8)9< 10, advance left
1 (3)4 (8)11> 10, retreat right
1 (3)3 (6)9< 10, advance left
2 (4)3 (6)10match, return (2, 3)

Five comparisons for six elements: linear, not the 15 pairs brute force would check.

Python
def two_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None:
    left, right = 0, len(nums) - 1
    while left < right:
        current = nums[left] + nums[right]
        if current == target:
            return left, right
        if current < target:
            left += 1   # nums[left] too small for any k <= right
        else:
            right -= 1  # nums[right] too big for any k >= left
    return None

Failure modes

  1. Non-monotonic evaluator. The discard argument needs the metric to move in one direction per pointer. For a product target with negatives, sorting does not give that: incrementing left past a negative value raises nums[left], which lowers the product against a positive right but raises it against a negative right. The elimination step is unsound and the pass can miss the answer.
  2. Enumerating all pairs. The linear bound is for finding one witness. If you must output every pair, the output itself can be $O(N^2)$, and duplicate handling has to advance pointers forward, never reset them backward, or the worst case degrades.
  3. Unsorted input. Sorting first costs $O(N \log N)$, which dominates the pass. If constant space is not required, a hash map gives $O(N)$ time and $O(N)$ space without sorting.

Detect a broken invariant by testing inputs where the metric is non-monotone (negatives, products, absolute values) and asserting the pass still finds a known witness.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-6

How does the three-pointer Dutch National Flag partitioning algorithm sort an array of three distinct values in O(n) time and O(1) space?

Answer

The Dutch National Flag (DNF) algorithm partitions an array containing three distinct keys (typically 0, 1, 2 or low, mid, high) in a single linear pass using three pointers that maintain four contiguous regions.

Invariant and Pointer Setup

Given three pointers (low, mid, and high) initialized to low = 0, mid = 0, and high = len(a) - 1, the array is divided into four regions at the start of each iteration:

  1. a[0 : low] contains elements strictly less than the pivot (e.g., 0).
  2. a[low : mid] contains elements equal to the pivot (e.g., 1).
  3. a[mid : high + 1] contains uninspected elements.
  4. a[high + 1 : n] contains elements strictly greater than the pivot (e.g., 2).

The loop runs while mid <= high. When mid > high, the uninspected region is empty, and the array is partitioned.

The Three Transitions

At each step, examine a[mid]:

  • If a[mid] == 0 (less than pivot): Swap a[low] with a[mid]. Advance both low += 1 and mid += 1. We advance mid because whatever was at a[low] was already processed and is known to be 1 (or mid == low, in which case 0 swaps with itself).
  • If a[mid] == 1 (equal to pivot): Advance mid += 1. The element belongs in the middle region; no swaps needed.
  • If a[mid] == 2 (greater than pivot): Swap a[mid] with a[high]. Decrement high -= 1. Do not advance mid: the element swapped from high into mid was uninspected and must be evaluated on the next iteration.
Python
def dnf_sort(nums: list[int]) -> None:
    low, mid, high = 0, 0, len(nums) - 1
    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:  # nums[mid] == 2
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1

Execution Trace

Tracing [2, 0, 2, 1, 1, 0]:

SteplowmidhighArray stateAction
Init005[2, 0, 2, 1, 1, 0]a[0] == 2: swap a[0], a[5], high = 4
1004[0, 0, 2, 1, 1, 2]a[0] == 0: swap a[0], a[0], low = 1, mid = 1
2114[0, 0, 2, 1, 1, 2]a[1] == 0: swap a[1], a[1], low = 2, mid = 2
3224[0, 0, 2, 1, 1, 2]a[2] == 2: swap a[2], a[4], high = 3
4223[0, 0, 1, 1, 2, 2]a[2] == 1: match mid, mid = 3
5233[0, 0, 1, 1, 2, 2]a[3] == 1: match mid, mid = 4
Term243mid > highDone

Complexity and Failure Modes

  • Complexity: $O(n)$ time and $O(1)$ auxiliary space. Every iteration either increments mid or decrements high, guaranteeing at most $n$ comparisons and swaps.
  • Trap / Failure Mode: Incrementing mid after swapping with high. If a[high] was a 0 or another 2, blindly incrementing mid skips inspection and places the value into the middle region, corrupting the invariant.
  • Stability: Like two-way Hoare partitioning, DNF partitioning is unstable; distant swaps reorder identical items.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2

How does the converging two-pointer pattern work on sorted arrays, and how do you guarantee no valid pairs are skipped when moving a pointer?

Answer

Two pointers on a sorted array: put lo at index 0 and hi at N-1. Compare a[lo] + a[hi] against the target. Equal: done. Less: every pair (lo, k) with k <= hi has a[lo] + a[k] <= a[lo] + a[hi] < target, so the entire row anchored at lo is dead; lo += 1. Greater: every pair (k, hi) with k >= lo has a[k] + a[hi] >= a[lo] + a[hi] > target, so the column anchored at hi is dead; hi -= 1. Each step eliminates one row or one column of the implicit N x N pair grid, and hi - lo shrinks by exactly 1, so the loop runs at most N-1 times. That elimination argument is the no-skip guarantee: the invariant is that any valid pair still lies inside the surviving box [lo, hi], and both moves preserve it.

Python
# Python 3.12
def two_sum_sorted(a, target):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        s = a[lo] + a[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None

Trace on a = [2, 5, 8, 9, 11, 15], target = 19:

Steplohia[lo]+a[hi]MovePairs eliminated
10 (2)5 (15)17 < 19lo=1(0,5),(0,4),(0,3),(0,2),(0,1)
21 (5)5 (15)20 > 19hi=4(1,5),(2,5),(3,5),(4,5)
31 (5)4 (11)16 < 19lo=2(1,4),(1,3),(1,2)
42 (8)4 (11)19 == 19return—

Four comparisons for six elements; the pair (2, 4) is found and nothing valid was skipped.

Trade-offs, when this is the wrong tool. The obvious alternative is a single-pass hash map: walk the array once, and for each a[i] check whether target - a[i] is already in the map. That is O(N) time and O(N) space, works on unsorted input, and returns indices in original order. Two pointers is O(N) time and O(1) space, but only after the array is sorted. If the input is not already sorted, sorting costs O(N log N) and destroys the original indices unless you carry (value, index) pairs: at which point the hash map is usually the better answer. Reach for two pointers when the array is already sorted, when memory is tight, or when you need the pair closest to a target (the same monotone move adapts directly). Reach for the hash map when the input is unsorted, when it is a stream you cannot sort, or when you need to count or enumerate all pairs.

Failure modes.

  • Unsorted input. The inequalities a[k] <= a[hi] and a[k] >= a[lo] break, and the algorithm discards live pairs. Detect it by asserting monotonicity in tests; never trust the caller.
  • Integer overflow. On C++/Java, a[lo] + a[hi] can overflow near INT_MAX. Compare a[lo] == target - a[hi] or widen to 64-bit.
  • Only one pair. The loop returns the first match. To enumerate all pairs, on a match do lo += 1; hi -= 1 and skip duplicate values on both sides, or you will miss pairs when equal values sit at both ends.
  • Duplicates. With repeated values, a naive lo += 1 after a match can skip a valid partner; the standard fix is to advance past equal runs deliberately rather than one index at a time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through same-direction pointers, including where engineers most often get it wrong.

Answer

What a strong candidate says first. Same-direction pointers are two indices that only ever move forward: a read (fast) pointer that visits every element, and a write or left pointer that advances only when an invariant holds. The read pointer advances unconditionally; the trailing pointer stalls. That asymmetry is the pattern: it keeps the pass O(n) while the two indices move at different rates. Two shapes cover almost everything you'll be asked: compaction (read/write, in-place filter) and sliding window (right expands, left contracts while the window is invalid).

Compaction. Keep the prefix [0, write) as the elements you've decided to keep, in order.

Python
def compact(a, keep):
    write = 0
    for read in range(len(a)):
        if keep(a[read]):
            a[write] = a[read]
            write += 1
    return write

Trace a = [0, 1, 0, 3, 12], keep = x != 0:

reada[read]keep?write afterarray
00no0[0,1,0,3,12]
11yes1[1,1,0,3,12]
20no1[1,1,0,3,12]
33yes2[1,3,0,3,12]
412yes3[1,3,12,3,12]

Returns 3; a[0:3] = [1, 3, 12]. The write index never exceeds read, so a[write] = a[read] can't clobber an unread element.

Sliding window. Right advances every step; left jumps to last[ch] + 1 when the incoming character is already inside the window.

Python
def longest_unique(s):
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

On "abcbd": right=3 ('b', last seen at 1) moves left to 2; right=4 ('d') gives window "cbd", best = 3. The answer is 3.

Where it goes wrong. The dominant bug is assuming both pointers advance once per iteration, which collapses the pattern into a fixed-offset comparison. In the window code the same mistake is left += 1 instead of left = last[ch] + 1: on "abcbd" that returns 4, because left moves only one step and the window "bcbd" is counted as valid. Detect both with property tests over inputs containing duplicates (random arrays over a small alphabet, or strings with repeats) not with the happy path.

Other failure modes: returning write + 1 instead of write (the kept prefix is [0, write), so the length is write); using compaction when keep depends on elements ahead of read, which breaks the prefix invariant; and aliasing when you reorder the writes so write can pass read.

Trade-offs. In-place same-direction pointers cost O(1) extra space and O(n) time but mutate the input and need a monotone predicate. A hash set or map costs O(n) space and answers "have I seen this anywhere in the window" in O(1) expected: that's why substring problems use the window-plus-map form; plain compaction can't look back. An output buffer is the simplest and safest when the input is read-only or shared, at O(n) space. Sorting first (O(n log n)) turns pair-sum on unsorted input into a two-pointer scan. Reach for the in-place form when memory is the constraint and mutation is allowed; reach for the map or buffer when you need arbitrary look-back or must preserve the input.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does in-place deduplication guarantee, and what does it deliberately leave open?

Answer

The guarantee. After in-place deduplication of a sorted array, the first k slots hold every distinct value exactly once, in the original relative order, and the function returns k. k equals the number of distinct values. Time is O(n) (one pass, each element read once) and extra space is O(1): no second buffer, the output overwrites the input.

What it leaves open. Everything at index k and beyond. The tail is unspecified: not "the removed duplicates", not sorted, not even necessarily the old values. The container's length is unchanged: only the logical length moved. And "duplicate" means whatever equality you passed in; keeping the last occurrence, merging records, or deduping by a key is a different contract, not a flag on this one.

Python
def dedupe(a):                    # a must be sorted
    if not a:
        return 0
    write = 1
    for read in range(1, len(a)):
        if a[read] != a[write - 1]:
            a[write] = a[read]
            write += 1
    return write

Trace on [1, 1, 2, 3, 3]:

reada[read]a[write-1]actionwritea
111equal, skip1[1,1,2,3,3]
221differ, a[1]=22[1,2,2,3,3]
332differ, a[2]=33[1,2,3,3,3]
433equal, skip3[1,2,3,3,3]

Returns 3. a[3:] is [3, 3] here, but nothing promises that: a different implementation could leave [2, 3] or anything else.

Failure modes.

  • Returning the array, or its full length, instead of k. Callers iterate the whole buffer and read the stale tail. It survives casual testing because a test whose input has no trailing duplicates never exposes it; assert len(result) == k on an input that ends in a run.
  • Calling it on unsorted input. The loop does not error: it silently emits a wrong prefix, because a[write-1] is no longer the last distinct value seen. Sortedness is a precondition, not a check.
  • Assuming the tail holds the removed elements. Some implementations leave them, some overwrite them.

Named contract. C++ std::unique returns a ForwardIt to the new logical end, states that values past it are unspecified, applies the predicate exactly max(0, last - first - 1) times, and requires the range sorted with respect to the predicate. Python has no in-place equivalent; dict.fromkeys(a) preserves order but allocates O(k).

When not to use it. If you need the removed elements, a stable dedupe that keeps the last occurrence, or dedupe by key with merging, this pass is the wrong tool: reach for a hash map or a second pass. In-place compaction is the right choice when the array is sorted, the caller only needs the prefix, and allocation is the cost you are avoiding.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do you maintain loop invariants during two-pointer and three-pointer array partitioning, and why does in-place partitioning inherently forfeit stability?

Answer

In-place array partitioning reorders elements around a predicate or pivot by dividing the array into active regions via pointers. The correctness of the scan rests entirely on maintaining clear loop invariants across each pointer transition.

1. Invariants in Two-Way Partitioning (Lomuto vs. Hoare)

In Lomuto's scheme (unidirectional), a write boundary i tracks the prefix where predicate(x) is true, while a scan pointer j explores unseen elements:

  • [0, i) satisfies predicate(x) == True
  • [i, j) satisfies predicate(x) == False
  • [j, n) is unexamined
Python
def lomuto_partition(a, predicate):
    i = 0
    for j in range(len(a)):
        if predicate(a[j]):
            a[i], a[j] = a[j], a[i]
            i += 1
    return i  # boundary between matching and non-matching

In Hoare's scheme (bidirectional), pointers converge from opposite ends:

  • left scans rightward until finding an element violating the left partition condition.
  • right scans leftward until finding an element violating the right partition condition.
  • Swapping a[left] and a[right] restores both sides, shrinking the unexamined interval [left + 1, right - 1] until the pointers cross.

2. Three-Way Partitioning (Dutch National Flag)

When partitioning around three states (e.g., < pivot, == pivot, > pivot), two pointers are insufficient without redundant passes. Edsger Dijkstra’s Dutch National Flag algorithm uses three pointers (low, mid, high) defining four distinct regions:

[ < pivot ] [ == pivot ] [ unexamined ] [ > pivot ]
0         low          mid            high        n-1
  • Invariant 1: a[0 : low] < pivot
  • Invariant 2: a[low : mid] == pivot
  • Invariant 3: a[mid : high + 1] is unexamined
  • Invariant 4: a[high + 1 : n] > pivot
Python
def dnf_partition(a, pivot):
    low = 0
    mid = 0
    high = len(a) - 1
    while mid <= high:
        if a[mid] < pivot:
            a[low], a[mid] = a[mid], a[low]
            low += 1
            mid += 1  # element swapped from low was already inspected (== pivot)
        elif a[mid] == pivot:
            mid += 1
        else:  # a[mid] > pivot
            a[mid], a[high] = a[high], a[mid]
            high -= 1 # mid does NOT advance; a[high] swapped into mid is unexamined
    return low, high

A critical invariant trap: when a[mid] > pivot, swapping with a[high] brings an uninspected value into a[mid]. Advancing mid here skips validation and corrupts the partition.

3. Why In-Place Partitioning Forfeits Stability

A partition algorithm is stable if elements satisfying the same condition preserve their original relative order. In-place partitioning achieves $O(1)$ auxiliary space by swapping elements across long strides over an unexamined middle region.

Consider [(2_a, True), (1, False), (2_b, True)] with predicate x == 2 using bidirectional or Lomuto partitioning:

  • Bidirectional swaps inverted elements across ends, reversing or shuffling relative positions.
  • In Lomuto partitioning, non-matching elements get displaced whenever a matching element is encountered later in the scan. If a = [False_1, False_2, True_1], processing True_1 swaps with index 0, jumping over False_2.

Preserving stability requires retaining arrival order. Without $O(N)$ auxiliary buffers or complex $O(N \log N)$ block-reversal algorithms (like in-place stable merges), an $O(N)$ single-pass partition using simple pointer swaps cannot guarantee stability.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does removing duplicates in pair search matter, and where is it irrelevant?

Answer

Short answer. Dedup matters when two things hold at once: the input can contain repeated values, and the output is defined as a set of value combinations. It is irrelevant when the input is distinct, when you return on the first match, or when the output is defined over indices or multiplicity: there, dedup is a no-op or a bug.

Where it matters. Sorted two-pointer pair search, and its 3Sum/4Sum extensions, report value pairs. Advancing both pointers by one after a match re-emits the same pair for every copy of a repeated value. The fix is to skip equal values at the moment of advancing, not to filter the result afterwards:

Python
# a sorted ascending, target int
while lo < hi:
    s = a[lo] + a[hi]
    if s == target:
        out.append((a[lo], a[hi]))
        lo += 1; hi -= 1
        while lo < hi and a[lo] == a[lo - 1]: lo += 1
        while lo < hi and a[hi] == a[hi + 1]: hi -= 1
    elif s < target: lo += 1
    else: hi -= 1

Trace on a = [2] * 10000, target 4: lo=0, hi=9999, s=4, append (2, 2), lo=1, hi=9998. The first skip loop walks lo to 9998 (a[lo] == a[lo-1] at every step), the second does nothing, and lo < hi is now false. One pair out. Remove the two skip loops and the same input emits 5000 pairs, one per pointer step, before the pointers meet. The loop is still O(n); the output is 5000x larger and the caller pays to dedup it.

3Sum adds the same skip on the outer index: if i > 0 and a[i] == a[i-1]: continue. There the blow-up is quadratic: an all-equal input yields O(n²) triples without the skips and one distinct triple with them.

Where it's irrelevant.

  • Input is distinct: a set, a permutation, a hash map keyed by value. The skip loops never fire; they cost one comparison per advance.
  • You return on the first match. "Find any pair" ends at the first hit, so no second pair is ever produced.
  • The output is over indices or multiplicity. "Count pairs i<j with a[i]+a[j]==target" wants every index pair. On [2] * 10000, target 4, the answer is C(10000, 2) = 49,995,000; dedup returns 1 and is wrong.
  • Hash-map two-sum. Keys collapse duplicates for free, so a single-pair search needs no skip logic at all.

Failure mode. Post-hoc dedup (set(out)) is the common wrong answer. It materialises every duplicate before discarding it (5000 tuples instead of 1 in the pair case, O(n²) in the 3Sum case) and it hides the blow-up from the caller. It survives casual testing because a distinct-value input passes either way; only a repeated-value input, or a large one, exposes the difference. Test with an input of identical values.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach reducing a triple to a pair to an engineer who has only seen it as a rule of thumb.

Answer

The 60-second answer. Sort the array, then fix the smallest index i of the triple and solve a two-sum on the suffix a[i+1:] with target -a[i]. The suffix is sorted, so converging pointers find that pair in one linear pass. Every triple has exactly one smallest index, so iterating i over 0..n-3 and running the pair search on each suffix enumerates each triple once: no misses, and no duplicate triples from the outer loop. Cost is O(n log n) for the sort plus O(n) per i: O(n^2) total, O(1) extra space beyond the sort. The reduction is what buys the exponent, not the pointer trick on its own.

Python
def three_sum(a, target=0):
    a = sorted(a)
    n = len(a)
    out = []
    for i in range(n - 2):
        if i > 0 and a[i] == a[i - 1]:
            continue                      # skip duplicate smallest elements
        lo, hi = i + 1, n - 1
        need = target - a[i]
        while lo < hi:
            s = a[lo] + a[hi]
            if s == need:
                out.append((a[i], a[lo], a[hi]))
                lo += 1
                hi -= 1
                while lo < hi and a[lo] == a[lo - 1]:
                    lo += 1
                while lo < hi and a[hi] == a[hi + 1]:
                    hi -= 1
            elif s < need:
                lo += 1
            else:
                hi -= 1
    return out

Trace on a = [-4, -1, -1, 0, 1, 2], target 0:

ia[i]needpointer walkhit
0-44(-1,2)=1, (-1,2)=1, (0,2)=2, (1,2)=3 → lo==hi—
1-11(-1,2)=1(-1,-1,2)
1-11after advancing past duplicates: (0,1)=1(-1,0,1)
2-1—skipped, equals a[1]—
300(1,2)=3 > 0 → hi=4, lo==hi—

Output: [(-1,-1,2), (-1,0,1)]. The two duplicate skips are doing different jobs: the outer one stops i=2 from re-finding (-1,-1,2), the inner ones stop the same pair from being emitted twice when a value repeats inside the suffix.

Why the exponent drops. At n = 2000, brute force examines C(2000,3) ≈ 1.33×10^9 triples. The two-pointer version does sum(n-1-i) ≈ n²/2 ≈ 2×10^6 pointer steps: roughly 660× fewer, and the sort is 2000·log2(2000) ≈ 22,000 comparisons on top.

When hashing beats sorting. For each i, walk j from i+1 upward, keeping a set of values already seen in the suffix, and test whether need - a[j] is in it. Same O(n^2) time, but O(n) extra memory and no sort. Add a[j] to the set after the lookup, or a repeated value reuses its own index and you emit a triple with two copies of one element. Reach for this when the input cannot be reordered (a stream, or a case where you must report original indices) and for the sorted version when memory is tight or the output has to come out ordered. Neither is strictly better; the memory-for-sort trade is the whole decision.

Failure modes. Duplicate triples from skipping only one of the two duplicate sites above. Off-by-one on the outer bound: range(n - 2) is required, since i = n-2 leaves a one-element suffix with no pair. And the hashing variant silently returning wrong triples when the set is built before the lookup instead of after.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Why is the greedy two-pointer approach optimal for Container With Most Water, and why can the pointer with the smaller height be safely discarded?

Answer

The two-pointer technique starts with left = 0 and right = n - 1 and shrinks the window by moving inward whichever boundary has the smaller height. This finds the global maximum area in $O(n)$ time and $O(1)$ space.

The search is optimal because moving the shorter line safely eliminates an entire subset of candidates without computing them.

The Invariant and Elimination Proof

Let the area bounded by indices $i$ and $j$ ($i < j$) be: $$\text{Area}(i, j) = (j - i) \times \min(h[i], h[j])$$

Suppose at step $(L, R)$ we have $h[L] \le h[R]$. Consider any candidate pair $(L, k)$ where $L < k < R$:

  1. Width decreases: $(k - L) < (R - L)$.
  2. Height cannot exceed $h[L]$: $\min(h[L], h[k]) \le h[L] = \min(h[L], h[R])$.

Therefore: $$\text{Area}(L, k) = (k - L) \times \min(h[L], h[k]) < (R - L) \times h[L] = \text{Area}(L, R)$$

No pairing involving index $L$ and any remaining inner index $k$ can ever beat the current area $\text{Area}(L, R)$. Index $L$ cannot participate in any future maximum, so discarding $L$ (doing left += 1) eliminates $R - L - 1$ sub-optimal states in $O(1)$ time without examining them. Symmetrically, if $h[R] < h[L]$, index $R$ is discarded by doing right -= 1.

Implementation

Python
def max_area(height: list[int]) -> int:
    left, right = 0, len(height) - 1
    best = 0
    while left < right:
        w = right - left
        hl, hr = height[left], height[right]
        if hl <= hr:
            area = w * hl
            left += 1
        else:
            area = w * hr
            right -= 1
        if area > best:
            best = area
    return best

Trace on a Bottleneck Case

Take height = [1, 8, 6, 2, 5, 4, 8, 3, 7], $n = 9$:

Stepleft ($h[L]$)right ($h[R]$)WidthAreaAction & Discard Justification
10 (1)8 (7)8$8 \times 1 = 8$$h[0] \le h[8] \implies$ discard index 0. Pairs $(0, 1)$ through $(0, 7)$ are strictly $< 8$.
21 (8)8 (7)7$7 \times 7 = 49$$h[8] < h[1] \implies$ discard index 8. Pairs $(2, 8)$ through $(7, 8)$ are strictly $< 49$.
31 (8)7 (3)6$6 \times 3 = 18$$h[7] < h[1] \implies$ discard index 7. Pairs $(2, 7)$ through $(6, 7)$ are strictly $< 18$.
41 (8)6 (8)5$5 \times 8 = 40$Equal heights; discarding either is safe (both cannot pair with inner lines to beat 40 with width $\le 4$). Discard 1.

Total iterations: $n - 1 = 8$, evaluating 8 pairs instead of $\binom{9}{2} = 36$ brute-force pairs.

Equal-Height Tie Breaking

When $h[L] == h[R]$, moving either pointer (or both) preserves optimality. With $h[L] = h[R] = H$, any interior pairing $(L, k)$ has height $\le H$ and width $< R - L$, so it yields area $< H \times (R - L)$. The same holds for $(k, R)$. Neither $L$ nor $R$ can form a larger container with any interior element, so incrementing $L$, decrementing $R$, or doing both simultaneously cannot drop the global maximum.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Given two sorted arrays, walk me through using one pointer per array to merge them into one sorted array, and how the same traversal finds their intersection: advance rule, termination, and complexity versus concatenate-and-sort?

Answer

Clarify first: both arrays sorted ascending, duplicates allowed, output is a new array. Descending order just flips the comparison. If one array is tiny, the two-pointer merge is the wrong tool: see below.

The invariant that makes it work: at every step, the smallest element not yet placed in the output sits at a[i] or b[j]. Everything before i in a and before j in b is already placed and is no larger than anything at or after the pointers. So comparing just those two candidates and emitting the smaller is safe; nothing behind either pointer can be smaller than the element you are about to write.

python def merge(a, b): i = j = 0 out = [] while i < len(a) and j < len(b): if a[i] <= b[j]: # <= keeps equal keys from a before b (stable) out.append(a[i]); i += 1 else: out.append(b[j]); j += 1 out.extend(a[i:]) # exactly one of these two is non-empty out.extend(b[j:]) return out

def intersect(a, b): i = j = 0 out = [] while i < len(a) and j < len(b): if a[i] < b[j]: i += 1 elif a[i] > b[j]: j += 1 else: out.append(a[i]); i += 1; j += 1 return out

Trace merge on a = [1,3,5,7], b = [2,3,6]:

stepi, jcompareemit
10,01 < 21
21,03 > 22
31,13 = 33 (from a)
42,15 > 33 (from b)
52,25 < 65
63,27 > 66
73,3j exhaustedextend a[3:] → 7

Result [1,2,3,3,5,6,7]. The same walk in intersect emits 3 at step 3 and stops when j hits len(b): one comparison per element, no set built.

Termination. The loop ends the moment either pointer runs off its array. The other array's remaining suffix is already sorted and every element in it is at least the last thing emitted, so you append it wholesale instead of continuing to compare. That is the step people drop when they write into a preallocated output buffer: the loop exits with i < len(a) and the tail never gets copied.

Cost. O(m+n) time, O(m+n) for the output (O(1) auxiliary beyond it). A general comparison sort of the concatenation is O((m+n) log(m+n)): with m = n = 10^6 that is roughly 2·10^6 · 21 ≈ 4.2·10^7 comparisons against at most m+n−1 ≈ 2·10^6 for the merge. About 20× fewer, and the gap widens with size. One honest caveat: CPython's sorted(a + b) is not a general comparison sort here. Timsort detects the two existing runs and merges them in linear time, so on CPython the shortcut is also O(m+n), and you should say that rather than claim a speedup you cannot demonstrate.

When not to use it. If one array is tiny, binary-search each of its elements into the larger one: O(m log n), no output-sized allocation, and bisect gives it to you. For an intersection where neither input is sorted, a hash set is O(m+n) expected time and often faster in Python than sorting first.

Failure modes to name. Advancing both pointers on an inequality skips elements: the merge silently loses data and the output is shorter than m+n. Advancing only one pointer on equality in intersect duplicates matches or loops forever. Assuming ascending order. And the dropped tail above. The cheap check for all of them: assert merge(a,b) == sorted(a+b) and intersect(a,b) == sorted(set(a) & set(b)) on random inputs, including empty and all-equal arrays.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of merging two sorted sequences?

Answer

Core answer. Refuse when the merge is repeated rather than one-shot, when sortedness is not an invariant the producer actually maintains, or when the merge is standing in for a set operation whose tie-break and duplicate semantics nobody has pinned down. A single merge of two genuinely sorted sequences is O(n) and streaming; refusing that is wrong. The refusal is about the design wrapped around the merge, not the merge itself.

1. Repeated merging. If the design merges k sequences by folding left, merge the running result with the next list, the cost is quadratic in k, because every merge re-walks everything already merged.

Arithmetic: k = 1000 lists of 10,000 elements, n = 10^7. A left fold does sum over i=2..1000 of i × 10,000 ≈ 5.0×10^9 comparisons. A k-way heap merge does n log2 k ≈ 10^7 × 10 = 1.0×10^8. That is ~50×. Refuse the fold and ask for a heap or a balanced pairwise merge.

ApproachComparisonsExtra memoryWhen it is right
One-shot 2-way mergenO(1) beyond outputtwo sorted inputs, merged once
Left-fold k-way~nk/2O(n) outputnever at scale
Heap k-wayn log2 kO(k) heapk sorted streams
Sort everythingn log nO(n)inputs are not sorted

2. Sortedness is not an invariant. The merge is silent when an input is out of order: it emits a wrong order, not an error. If the producer appends without maintaining order, the design is broken and the merge hides it. Refuse unless there is a check at the boundary: an assertion that each sequence is monotonic, or a property test that shuffles and re-sorts before merging.

3. Tie-break and duplicates are semantics, not details. a[i] <= b[j] takes the left element on ties, which is what makes the merge stable. If the design needs the newer sequence to win ties, that comparison is wrong. And a merge does not dedupe: equal heads are both emitted unless you advance both pointers. If the design says "merge and dedupe" and the code only merges, duplicate rows survive into the output.

Failure modes. Truncation from a missing drain: the tail of the longer sequence is dropped, and casual tests miss it because the happy path often has equal lengths. Wrong order from a broken sortedness invariant. Duplicate rows from a merge used as a join. Each is detected by a boundary assertion or a property test, not by reading the merge loop.

When not to refuse. Two sorted inputs, merged once, consumed as a stream: that is optimal. O(n) time and O(1) extra space beyond the output. Refusing it buys you a sort you did not need.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain merging in place from the back without using the usual slogan?

Answer

Assumptions first. a holds m sorted elements followed by n spare slots; b holds n sorted elements; the result must land in a. The reason to write from the back is an invariant you can state and check, not a rule of thumb: while b still has unread elements, the write slot is strictly to the right of a's last unread element, so the slot you are about to write is never a slot you still need to read.

Make it exact. Let i be the last unread index of a, j the last unread index of b, w the last unwritten slot of a. At the top of every iteration:

w - i = j + 1

  • Start: w - i = (m+n-1) - (m-1) = n = j + 1.
  • Take from a: w and i both drop by one, so w - i is unchanged.
  • Take from b: w drops by one and i does not, so w - i drops by one. Exactly as j + 1 does.

The loop runs only while j >= 0, so j + 1 >= 1, so w - i >= 1, i.e. w > i. The write slot is always past a's unread tail. When j reaches -1, b is exhausted and w = i, so the surviving a[0..i] are already in their final positions: no copy step.

Python
# Python 3
def merge(a, m, b, n):        # a[0:m] sorted, a[m:m+n] spare
    i, j, w = m - 1, n - 1, m + n - 1
    while j >= 0:
        if i >= 0 and a[i] > b[j]:
            a[w] = a[i]; i -= 1
        else:
            a[w] = b[j]; j -= 1
        w -= 1

Trace a = [4,5,6,0,0,0], m = 3, b = [1,2,3], n = 3:

stepijww-icomparewritea after
122536 > 3a[5] = 6[4,5,6,0,0,6]
212435 > 3a[4] = 5[4,5,6,0,5,6]
302334 > 3a[3] = 4[4,5,6,4,5,6]
4-1223i < 0a[2] = 3[4,5,3,4,5,6]
5-1112i < 0a[1] = 2[4,2,3,4,5,6]
6-1001i < 0a[0] = 1[1,2,3,4,5,6]

j is now -1 and w = i = -1; nothing is left to copy.

Why the forward version fails on the same inputs. Writing from index 0 with i = j = w = 0, the write pointer is w = i + j: it starts level with the read pointer and only ever moves right. The first write that is not a no-op lands on a[i+j], which is still unread whenever i+j <= m-1.

stepijwcomparewritea after
1000a[0]=4 > b[0]=1a[0] = 1[1,5,6,0,0,0]
2011a[0]=1 <= b[1]=2a[1] = a[0] = 1[1,1,6,0,0,0]
3112a[1]=1 <= b[1]=2a[2] = a[1] = 1[1,1,1,0,0,0]
4213a[2]=1 <= b[1]=2a[3] = a[2] = 1[1,1,1,1,0,0]
5314i = m, stopcopy b[1] = 2[1,1,1,1,2,0]
6325copy b[2] = 3[1,1,1,1,2,3]

Result [1,1,1,1,2,3]; 4, 5 and 6 are gone. Step 1 is the fatal one: w = i = 0, so a[0] = 1 overwrites the unread 4 before it is ever emitted, and every later read of a[i] reads a value the merge itself wrote.

When it bites. The forward merge is correct only when every element of a is at most every element of b: the one case where b is never touched until a is exhausted. Any interleaving corrupts, because the first take from b has j = 0 and i < m, so it writes to a[i] and destroys an unread element. Test the extreme case (all of b below all of a) explicitly; a test with a entirely below b passes and tells you nothing.

Stability. The comparison decides it. a[i] > b[j] sends b's element first on ties, so equal keys from b land before equal keys from a. If a is the left run and you need stability, use a[i] >= b[j].

When not to use it. If the destination is a separate array, forward is simpler and the invariant is unnecessary. Back-filling earns its keep only when the output has to live in a's tail.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does finding the middle in one pass change if the workload grows by two orders of magnitude?

Answer

Assumption: a singly linked list in RAM, and "one pass" means the two-pointer (slow/fast) walk. Under that assumption, two orders of magnitude change nothing asymptotically. The walk is O(n) time and O(1) extra space at 1M nodes and at 100M nodes alike; 100× the nodes is 100× the steps, linear, with no cliff and no new failure mode. The premise only changes the answer when 100× pushes the list out of RAM, because then the cost stops being step count and becomes one random memory access per node.

The walk. fast advances two nodes per iteration, slow one, so when fast runs off the end slow has covered half the distance by construction: no length precomputation.

Python
# Python 3.12; nodes are 1 -> 2 -> 3 -> 4 -> None
def second_middle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow          # 3

def first_middle(head):
    slow = fast = head
    while fast.next and fast.next.next:
        slow = slow.next
        fast = fast.next.next
    return slow          # 2

Trace second_middle on 1→2→3→4: start slow=1, fast=1. Iter 1: fast=1 and fast.next=2 are truthy → slow=2, fast=3. Iter 2: fast=3 and fast.next=4 truthy → slow=3, fast=None. Loop exits, returns 3. first_middle: iter 1 → slow=2, fast=3; iter 2 tests fast.next=4 and fast.next.next=None → exits, returns 2.

What 100× actually moves. Figures illustrative, 16 bytes per node (8-byte value + 8-byte pointer):

1M nodes100M nodes
bytes16 MB1.6 GB
fits inL3/DRAMDRAM, possibly swap
steps1M100M
in-RAM walk, contiguous~1 ms~0.1 s
in-RAM walk, scattered~0.1 s~10 s
NVMe, one random read per node~100 s~2.8 h

Where it breaks. Pointer chasing is a dependent load chain: each fast = fast.next.next cannot issue until the previous load returns. At 1M nodes the list sits in cache and the walk is bandwidth-bound; at 100M it is DRAM-latency-bound, and if the nodes are scattered the same O(n) walk costs ~100 ns per step instead of ~1 ns: a 100× wall-clock spread from memory layout alone, invisible in the step count. If the list is disk-resident, every node is a random read: 100M × ~100 µs ≈ 2.8 h on NVMe, and a count-then-walk two-pass approach doubles it. Nothing in the algorithm changed; everything in the memory hierarchy did.

Alternatives. If you can rewind, count the length then walk n/2: same O(n) time, O(1) space, two passes, so 2× I/O on disk. If the data is an array, the middle is an O(1) index; the one-pass trick exists only because linked lists cannot index. If it is a stream you cannot rewind, the two-pointer walk is unavailable: you must buffer the first half, O(n) space (50M × 16 B = 800 MB at 100M elements), or accept a sampled middle.

Failure mode to keep. Even-length lists have two middles and the loop condition picks which: the two functions above return 3 and 2 on the same input. Callers usually care, and casual testing on odd-length inputs hides it.

What would change the decision: if the list is disk-resident or a stream, the two-pointer walk is the wrong tool regardless of scale; if it is in RAM, scale is irrelevant and the only real decision is first versus second middle.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How would you test a claim that the system depends on fast and slow pointers?

Answer

Treat the claim as a hypothesis with three falsifiable predictions, then test each one. "The system depends on fast and slow pointers" means the cycle detection is Floyd's: two pointers at different speeds, O(1) extra space, meeting inside the cycle. Each of those is separately checkable, and any one failing falsifies the claim no matter what the code comment says.

1. Memory stays flat as the sequence grows. Floyd's uses two pointers and nothing else. Run the detector on sequences of 10^3, 10^5 and 10^7 nodes and watch resident memory or allocation count. If it grows linearly, the system is keeping a visited set, not running Floyd's.

2. The meeting point is inside the cycle, not at its entry. Construct a cycle whose entry is not the head and log the meeting node. On 1→2→3→4→5→3 (entry 3, cycle length 3):

Python
slow = fast = head
steps = 0
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
    steps += 1
    if slow is fast: break

Trace: step 1 gives slow=2, fast=3; step 2 gives slow=3, fast=5; step 3 gives slow=4, fast=4. They meet at 4, while the entry is 3. If your system reports the meeting node as the entry, it is wrong, or it is not Floyd's. Locating the entry needs a second walk: reset one pointer to the head and advance both one step at a time; from head=1 and meeting=4 that walk hits 3 on the third step.

3. Step count is bounded by n. The pointers meet within μ + λ steps (μ = distance to entry, λ = cycle length), so a counter that throws after n+1 steps is a cheap tripwire. If it fires, either the speed ratio is 1 (both pointers move together and never meet) or the loop guard is missing.

Alternatives, and when each wins. A visited hash set gives the entry directly in one pass at O(n) space: use it when memory is cheap and you need the entry without a second walk. Brent's algorithm is also O(1) space but does roughly half the pointer dereferences of Floyd's and yields the cycle length directly: use it when dereferencing is the expensive operation. A plain step counter bounded by a known maximum length is simplest of all, but only when you actually have that bound.

Failure modes to test for. Even-length acyclic lists where fast lands exactly on the last node: the fast and fast.next guard must not dereference null; test with a 2-node list. Cycles entered at the head, where meeting point and entry coincide and hide the bug in prediction 2. And streams you cannot re-traverse, where the second phase from the head is impossible, if the system needs the entry, Floyd's alone is the wrong tool.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What would you measure before treating locating the cycle entry as settled?

Answer

The algorithm is a proof, not a measurement, so what you measure is whether the proof's assumptions hold on the data you actually have. Three things, in order.

1. Entry correctness against an oracle. A visited-set walk gives ground truth: the first node seen twice is the entry. Run both over randomized lists (tail ∈ [0, 10⁴], cycle ∈ [1, 10⁴], 10⁵ cases) and count mismatches. The pass criterion is exactly 0. Include the degenerate shapes that off-by-one errors hide in: tail = 0 (entry is the head), cycle = 1 (self-loop), cycle = n (the whole list is the cycle). Those three are where the second phase's loop condition decides the answer.

2. The invariant and the iteration bound. Assert per case that tail ≡ distance(meet → entry) (mod cycle). Count iterations too: phase 1 ≤ tail + cycle, phase 2 = tail exactly, so total ≤ 2·tail + cycle ≤ 2n. A counter that exceeds that bound means the pointers are not advancing the way you think.

Worked trace, tail = 3, cycle = 4, nodes 0→1→2→3→4→5→6→3:

Python
def floyd_entry(head):
    slow = fast = head
    phase1 = 0
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
        phase1 += 1
        if slow is fast:
            break
    else:
        return None, phase1, 0        # tail ended: no cycle
    ptr = head
    phase2 = 0
    while ptr is not slow:
        ptr = ptr.next
        slow = slow.next
        phase2 += 1
    return ptr, phase1, phase2

Phase 1: (1,2), (2,4), (3,6), (4,4). Meet at node 4 after 4 iterations. Phase 2: (0,4), (1,5), (2,6), (3,3). 3 iterations, entry 3. Phase 2 iterations = tail = 3, total 7 ≤ 2·3 + 4 = 10. The invariant: distance(head→entry) = 3, distance(meet→entry) = 4→5→6→3 = 3, and 3 ≡ 3 (mod 4).

3. Cost, against the alternative. Floyd is O(1) memory but two passes of pointer chasing; a visited set is one pass and O(n) memory. Measure both at the real list size. Illustrative: at 10⁶ nodes each step is a dependent load, so ~100 ns per DRAM miss → ~100 ms for phase 1 plus ~tail steps for phase 2. The visited set costs ≈45 MB by arithmetic (2²¹ table slots × 8 B + 10⁶ int objects × 28 B on CPython 3.12). If the list is short or already in cache, the set wins on wall time; if it is long and memory-bound, Floyd wins.

MeasureMethodPass criterion
Entry correctnessvs visited-set oracle, 10⁵ random lists0 mismatches
Invarianttail ≡ dist(meet→entry) mod cycleholds every case
Iteration boundcounter≤ 2·tail + cycle
Degenerate shapestail = 0, cycle = 1, cycle = nentry correct
Latencywall time at n = 10⁶~100 ms (illustrative)
MemoryRSS delta vs visited setO(1) vs ~45 MB

Failure modes. Advancing the two phase-2 pointers at different rates breaks the modular argument and lands inside the cycle, not at its entry: the oracle comparison catches it, a happy-path test does not. Reusing the meeting pointer before phase 2 starts (aliasing) silently shifts the entry by one. A 32-bit iteration counter overflows past 2³¹ nodes; use 64-bit.

When not to use it. If you already maintain a visited set (graph traversal, dedup) you have the entry for free and Floyd buys nothing. If the structure is an array of indices rather than pointers, the set is cache-friendly and often faster.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does index stability under sorting force that a junior answer usually skips?

Answer

The 90-second answer. Sorting is a lossy operation on positions: it gives you the order you asked for and throws away the mapping from each value back to where it came from. So the moment the question says "return the indices" rather than "return the values", you have to decide how to carry that mapping, and every option costs something. Two ways: carry a permutation alongside the sort (numpy's argsort, or decorate-sort-undecorate in plain Python), which costs an extra O(n) array; or don't sort at all. A heap or a hash gives you the top-k indices in O(n log k) or O(n) without ever reordering. The trade-off is memory and a second pass versus the simplicity of one sort. There's a second axis a junior answer misses: if ties are broken by the sort, you need a stable sort, and stability is not free and not the default everywhere.

Mechanism. argsort doesn't sort the data; it returns the permutation that would sort it: an array of original indices in sorted order. That permutation is the index mapping, and it's the thing you index back into. Stability is orthogonal: a stable sort preserves the relative order of equal keys, so if you sort by value and two values are equal, their original indices stay ascending. That's what makes "the index of the maximum" deterministic when there are ties.

Python
import numpy as np
a = np.array([30, 10, 20, 10])
np.argsort(a)                  # [1, 3, 2, 0]  (default kind='quicksort', not stable)
np.argsort(a, kind='stable')   # [1, 3, 2, 0]  guaranteed: the two 10s keep index order

Trace: values are 30, 10, 20, 10. Ascending order is 10, 10, 20, 30 → indices 1, 3, 2, 0. The default quicksort may return the two 10s in either order; kind='stable' pins them to 1 then 3.

If you only need the top k, skip the full sort:

Python
import heapq
a = [30, 10, 20, 10]
heapq.nlargest(2, range(len(a)), key=a.__getitem__)   # [0, 2]

Trace: keys are a[0]=30, a[1]=10, a[2]=20, a[3]=10; the two largest are 30 (index 0) and 20 (index 2). O(n log k) time, O(k) extra space, and a is never reordered.

Cost. The permutation is one int64 per element: 8 bytes, so 80 MB at n=10⁷. Decorate-sort-undecorate in pure Python is far heavier: each (value, index) tuple is ~56 bytes plus the int objects it references, roughly 110 bytes per element, over 1 GB at the same n. That gap is the reason to reach for argsort rather than a list of tuples when n is large.

Failure modes. Sorting in place and then reporting positions returns indices into the sorted array, which mean nothing to the caller, and it passes casual tests because small inputs often have the identity permutation. Relying on an unstable sort to break ties makes "the index of the max" nondeterministic across runs and platforms. Both are caught by a test with duplicate keys and a shuffled input, not by the happy path.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does immutability of the input interact with rollback, and where do people ignore that?

Answer

Clarify first. "Rollback" is ambiguous here: a database transaction, a pipeline checkpoint, or an algorithm undoing its own partial state. The interaction is the same in all three, so I'll answer the general case: an operation fails partway and something has to undo it. The assumption that matters is whether the input is a place you wrote to.

Direct answer. If the input is immutable, rollback is free. You never wrote into it, so recovery is "drop the derived state and read the input again." If the input is mutable and you wrote into it, the original is gone, and rollback now costs an undo log or a copy taken before the first write. Immutability doesn't just prevent aliasing bugs: it moves rollback from O(work done) to O(1).

The mechanism, traced. A function that consumes its argument by mutating it cannot be retried:

Python
def drain(queue):
    out = []
    while queue:
        item = queue.pop()           # mutates the caller's list
        out.append(transform(item))  # may raise
    return out

q = [1, 2, 3]
try:
    drain(q)
except ValueError:
    pass
q   # [1]

Step by step: pop() takes from the end, so the first iteration removes 3 and transform(3) succeeds. The second removes 2 and transform(2) raises. The exception unwinds, out dies with the frame, and q is now [1]. A retry drains only [1]: two of three items are gone, and nothing raised to say so. The immutable version has no such state to lose:

Python
def drain(queue):
    out = []
    for item in queue:               # no mutation
        out.append(transform(item))
    return out

Retry re-reads the full input; rollback is dropping out.

input mutated in placeinput immutable
rollback costO(work done) undo log, or an up-front copyO(1): drop derived state, re-read input
retry safetyunsafe unless you snapshottedsafe by construction
extra memoryproportional to the mutationnone beyond the output

This is why MVCC exists. Postgres never overwrites a row in place; a rollback aborts the transaction and the prior row versions are still on disk, so undo is a visibility change, not a byte-level restore. Copy-on-write filesystems (ZFS, btrfs) get the same property from snapshots. An engine that updates in place instead needs an undo segment or WAL, and its rollback cost scales with how much it wrote.

Where people ignore it.

  1. Retry loops over a mutated buffer: the drain case above. The function looks side-effect-free because it returns a value; it isn't.
  2. Backtracking search that mutates a shared candidate list and "restores" it by re-sorting. Re-sorting is not the inverse of the mutation. Restore must be the exact inverse (push what you popped), or you pass a fresh list down and let the old one be garbage.
  3. Assuming a call is idempotent because it takes an argument by value in one language and by reference in another.

Detection. Snapshot the input before the call and assert equality after; or call the function twice on the same object and compare results: a different second result means the input was consumed. Both are cheap enough to leave in a test suite.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

A vendor promises palindrome checks is handled for you. What do you still own?

Answer

The vendor owns the comparison loop. You still own four things: the definition of equality, the input contract, the edge-case semantics, and the cost/latency envelope. Get any of those wrong and the vendor returns a correct answer to a question you didn't ask.

1. The definition of equality. "Palindrome" is underspecified. Does case matter? Punctuation? Whitespace? Which Unicode normalization form? A vendor comparing code points and a product comparing grapheme clusters disagree on real inputs.

Python
import unicodedata
s = "e\u0301"      # e + combining acute accent
t = "\u00e9"       # é precomposed
s == t                                        # False
unicodedata.normalize("NFC", s) == unicodedata.normalize("NFC", t)  # True

If the vendor compares raw code points, "e\u0301...\u0301e" returns False even though it is a palindrome under NFC. You own deciding which form is canonical and either normalizing before the call or documenting that the vendor's answer means code-point equality.

2. The input contract. Who strips ignorable characters, and by which rule? Python's str.isalnum() is Unicode-aware; a regex [^a-z0-9] is not. The vendor's "ignore punctuation" may drop _ but keep -, or the reverse. You own the spec and the test that pins it.

3. Edge-case semantics. These are the ones that bite in production:

InputQuestion you must answer
""palindrome? (usually yes)
" "palindrome after stripping?
"😀a😀"does reversal split surrogate pairs?
"e\u0301" vs "\u00e9"which normalization?
"ab"trivially no, but is the empty-after-strip case handled?

Java's char-based reversal breaks astral-plane characters because a code point above U+FFFF is two chars; Python 3 strings are code points and don't. If the vendor is Java-backed, emoji palindromes are a real failure. Detect it with a corpus of astral characters, not with the happy path.

4. Cost and latency. Per-call pricing turns a free local check into a line item. Illustratively, at $0.0001/call and 50M checks/day that is $5,000/day, roughly $150k/month. A local is_palindrome for strings under, say, 64 bytes costs nothing and removes the network hop; reserve the vendor for the long tail or the cases where its normalization is the contract.

Failure modes and detection. The vendor's answer is correct for its definition, so the failure is always a definition mismatch, not a bug. Detect it by pinning a golden corpus: composed/decomposed pairs, astral characters, empty and whitespace-only strings, mixed-script input, and running it against the vendor on every version bump. Normalization behavior is exactly the kind of thing that changes silently.

What you don't own: the loop, the pointer arithmetic, the O(n) walk. Don't reimplement it to "be safe" unless the cost model or the normalization contract forces you to.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on two pointers versus binary search, and what does not?

Answer

The section earns its place only if it changes what the on-call engineer does in the next minute. So it carries three things: the decision rule, the precondition that rule rests on, and the check that confirms the precondition. Everything else (the derivation, the complexity proof, the general "which is better" argument) is cut.

The rule: if both the data and the query batch are sorted, one merge walk answers the whole batch in a single pass. If the queries arrive unordered or isolated, run one binary search per query. That is the whole decision, and it is the first line of the section.

The precondition is the part people get wrong. The walk keeps a single index j that only moves forward. That is what makes it linear, and it is also what makes it silently wrong the moment a query is smaller than the one before it. So the section states the precondition as an assertion the caller can paste, not as a comment.

Python
import bisect

def lookup_all(data, queries):
    """data and queries must both be sorted ascending."""
    out, j = [], 0
    for q in queries:
        while j < len(data) and data[j] < q:
            j += 1
        out.append(j)          # first index with data[j] >= q
    return out

Trace data = [10, 20, 30, 40, 50], queries = [15, 35, 45]:

  • q=15: j 0→1 (10 < 15), stops at data[1]=20 → out=[1]
  • q=35: j 1→3 (20, 30 < 35), stops at data[3]=40 → out=[1, 3]
  • q=45: j 3→4 (40 < 45), stops at data[4]=50 → out=[1, 3, 4]

Four comparisons. Three bisect_left calls return the same indices in nine. j never resets: that is the whole reason the sorted-queries precondition is load-bearing.

Cost at the sizes this service sees: 100,000 sorted queries against 1,000,000 elements. The walk does 1,000,000 advances plus 100,000 failed checks = 1,100,000 comparisons. 100,000 bisect_left calls at roughly 20 probes each = 2,000,000. Both finish in well under a second, so the section should say plainly that the choice is not worth paging anyone over: that sentence is what stops the escalation.

Failure mode: unsorted queries return wrong indices with no error. Detection is assert queries == sorted(queries) in the caller, or a spot-check of a sample against bisect_left. Both are one line, and both belong in the section.

What does not belong: the proof that the walk is O(n + m), the textbook definition of two pointers, benchmark numbers from a developer laptop, and "consider load testing". Nothing follows from it. And the general argument about which technique is better: it has no operator action attached, so it is the first thing to cut when the section runs long.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is the cost of sorting first?

Answer

Read the diff for the sort first, then ask three things before writing a comment: what bounds n, is this on a hot path, and what does the ordering buy. Those answers decide whether I approve, request a change, or ask for a benchmark.

The comment I leave

Python
def find_pairs(events, target):
    events.sort()                    # mutates the caller's list
    lo, hi = 0, len(events) - 1
    out = []
    while lo < hi:
        s = events[lo] + events[hi]
        if s == target:
            out.append((events[lo], events[hi])); lo += 1; hi -= 1
        elif s < target: lo += 1
        else: hi -= 1
    return out

Three comments, in the order they would block a merge:

  1. events.sort() mutates the caller's list. If that is not part of the contract, use sorted(events), and note the copy allocates a second list of n pointers, 8n bytes on 64-bit CPython, so 80 MB at n = 10^7 held for the duration of the sort.
  2. The sort is O(n log n) and dominates the O(n) walk. If the caller only needs existence, a set gives O(n) expected. If it needs the pairs, the sort is buying constant extra space and ordered output: put that in the docstring, because it is the trade being made.
  3. If events holds objects, key= runs once per element, not once per comparison (CPython applies the key to each record before sorting). A key that hits the network or a lazy property is n round trips, not n log n.

The arithmetic that decides it

n = 10^7 events. Comparisons ≈ n log₂ n ≈ 10^7 × 23.25 ≈ 2.3 × 10^8. The walk is 10^7 steps. The sort is ~23× the walk: log₂ n, exactly. So if the walk measures 40 ms, the sort lands near a second, and that is the number to put in the review rather than "sorting is slow".

Alternatives to name in the comment

NeedSort-firstAlternativeCost
pair existsO(n log n)hash setO(n) expected, O(n) space
top k of nO(n log n)heapq.nlargest(k, …)O(n log k)
dedupeO(n log n)set / dictO(n) expected
ordered outputO(n log n)—the sort is the point
small bounded int keysO(n log n)counting sortO(n + k)
rows already in a DBsort in appORDER BY on an indexno app-side sort

What I check beyond the sort itself

  • Sort inside a loop: O(n² log n), and it is usually a missing pre-sort.
  • Stability: Python's sort is stable, so ties keep input order. Java's Arrays.sort on primitives is not, if this is ported, tie order changes.
  • Nearly-sorted input: Timsort is O(n) on runs, so a "sort" over data the database already ordered is nearly free. Check before demanding a rewrite.

Decision

n bounded at 10^4 or less: approve. 10^4 × 13 ≈ 1.3 × 10^5 comparisons is noise. Unbounded n on a request path: request the hash alternative or a benchmark on production-shaped data, and say which number would change my mind.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of the trapping-water two-pointer argument?

Answer

The failure to inject is a "far wall" input: a tall wall sitting beyond the pointer, so the current height at the pointer is small but the running maximum is what actually bounds the water.

Two inputs do the job:

  • [3, 0, 0, 2] → correct answer 4
  • [5, 0, 0, 0, 4] → correct answer 12

A team that understands the invariant returns 4 and 12. A team that memorized the loop and substituted the current heights for the running maxima returns 0 on both. That gap is the whole test.

Why it discriminates. The invariant is: keep lmax = max(h[0..lo]) and rmax = max(h[hi..n-1]). If lmax <= rmax, the water above lo is exactly lmax - h[lo], because the right side already guarantees a wall at least rmax >= lmax tall, so the left maximum is the binding one. Advance lo. Otherwise the symmetric case holds for hi. The bound is always a running maximum, never h[lo] or h[hi].

Python
def trap(h):
    lo, hi = 0, len(h) - 1
    lmax = rmax = water = 0
    while lo <= hi:
        if lmax <= rmax:
            lmax = max(lmax, h[lo])
            water += lmax - h[lo]
            lo += 1
        else:
            rmax = max(rmax, h[hi])
            water += rmax - h[hi]
            hi -= 1
    return water

Trace on [3, 0, 0, 2]:

steplo, hilmax, rmaxwater
10, 33, 00
21, 33, 20
31, 23, 22
41, 13, 24

Returns 4.

The buggy variant replaces the running maxima with the current heights:

Python
water += min(h[lo], h[hi]) - h[lo]   # when moving lo

On [3, 0, 0, 2] it never sees a bound above the current heights, adds 0 at every step, and returns 0. It fails exactly when a taller wall lies beyond the pointer, and survives hand-picked inputs where the tallest wall is one of the two ends being compared, which is why casual testing misses it.

Second failure to inject: pointer choice and equal heights. The invariant only holds if you advance the side with the smaller running maximum. Inject [2, 0, 2] → 2 (the lmax == rmax branch must not change the answer), monotonic inputs [1, 2, 3, 4] → 0 and [4, 3, 2, 1] → 0, and empty and single-element arrays → 0.

Trade-off. The two-pointer version is O(n) time, O(1) space. The prefix/suffix-maximum version is also O(n) time but O(n) space, and it is easier to prove and to debug because each index's bound is materialized. Use the array version as the oracle in a randomized test against the two-pointer version; prefer it directly when you need per-index water values or when reviewers don't trust the invariant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about constant space as the real benefit?

Answer

The claim under test: two pointers beats a hash set because the walk is O(1) space, and that is what decides the choice.

The experiment: measure peak auxiliary memory of the whole pipeline, not the walk, at two values of n, and compare slopes. Two data points are enough. If the two-pointer slope is nonzero, "constant space" is false.

Python
import random, tracemalloc

def measure(fn):
    tracemalloc.start()
    tracemalloc.reset_peak()
    fn()
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak / 2**20                      # MiB

def build(n):
    data = list(range(n))
    random.shuffle(data)                     # make the sort do real work
    return data

def hash_path(data):
    seen = set()
    for x in data:
        seen.add(x)                          # no early exit: we measure memory

def two_pointer_path(data):
    a = sorted(data)                         # the precondition, not the walk
    i, j = 0, len(a) - 1
    while i < j:
        s = a[i] + a[j]
        if s == 2 * len(a):
            return
        if s < 2 * len(a):
            i += 1
        else:
            j -= 1

for n in (500_000, 1_000_000):
    data = build(n)                          # allocated before tracing starts
    print(n,
          f"hash {measure(lambda: hash_path(data)):.1f}",
          f"two  {measure(lambda: two_pointer_path(data)):.1f}")

What it prints (CPython 3.12, Linux x86-64; these are the figures the arithmetic predicts: confirm on your box):

500000 hash 16.0 two  6.0
1000000 hash 32.0 two 12.0

Reading it. The hash path's peak is the set table: CPython sizes it to 2^21 slots at 16 bytes each for 1M distinct ints = 32 MiB. The two-pointer path's peak is sorted(): an 8 MiB copy of the list plus Timsort's merge buffer of up to n/2 pointers = 4 MiB, so ~12 MiB. Double n and both double. The two-pointer pipeline is O(n), not O(1): it just carries a ~2.7x smaller constant.

Falsification condition. If the two-pointer peak grows with n, the "constant space" claim is dead as stated. It does. The walk carries two integers, but the walk is only reachable after sorting, and sorting is O(n) in CPython. The claim is about the walk; the decision is about the pipeline.

When the claim survives. If the input arrives already sorted, or you may sort in place and the caller does not need the original order, and your sort is O(1) auxiliary (heapsort, or C's in-place quicksort at O(log n) stack), then the hash set is the only structure adding O(n) and the walk really is O(1). That is the case where constant space is the real benefit. The experiment that separates the two: feed both pipelines the same already-sorted array and re-measure. The hash line still climbs; the two-pointer line goes flat.

Traps in the experiment itself.

  • resource.getrusage(RUSAGE_SELF).ru_maxrss is a high-water mark that never falls. Run both pipelines in one process with it and the second measurement inherits the first's peak. Use tracemalloc.reset_peak() or separate processes.
  • tracemalloc sees Python allocations only, not numpy buffers or OS page cache.
  • Measuring the walk alone (two integers) proves nothing; it is trivially O(1). Measure the pipeline.
  • If the hash loop breaks on the first duplicate, the set never grows and you measure nothing. Use distinct input or drop the early exit.

The honest claim. "Two pointers uses less auxiliary memory than a hash set, by a constant factor, once the input is sorted", not "constant space." The input itself is already O(n) (8 bytes per pointer plus the int objects), so you have paid linear memory before either algorithm starts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document recognising the pattern so the next owner can operate it?

Answer

The doc that lets the next owner operate the pattern is a decision record with a runnable precondition, not a description of the pattern. One page, three parts: the check that decides whether two pointers applies, a counterexample that fails the check, and the failure signature with how to detect it. If the next owner can run the check and read the counterexample, they decide without re-deriving the argument.

The check is executable, not prose. For the sorted pair-sum family:

Python
# Python 3.12
def two_sum_sorted(nums, target):
    assert all(nums[i] <= nums[i+1] for i in range(len(nums)-1)), \
        "two pointers needs sorted input; use a hash map otherwise"
    l, r = 0, len(nums) - 1
    while l < r:
        s = nums[l] + nums[r]
        if s == target:
            return (l, r)
        if s < target:
            l += 1
        else:
            r -= 1
    return None

Trace it on nums = [1, 3, 4, 6, 8, 11], target = 10:

  • l=0, r=5: 1+11=12 > 10 → r=4
  • l=0, r=4: 1+8=9 < 10 → l=1
  • l=1, r=4: 3+8=11 > 10 → r=3
  • l=1, r=3: 3+6=9 < 10 → l=2
  • l=2, r=3: 4+6=10 → return (2, 3)

Five iterations, no pair revisited. That trace is the doc's proof that the elimination argument holds.

The counterexample is the part most docs omit. nums = [4, 1, 6, 3], target = 10: the guard fires before the loop runs. A hash map returns (0, 2) in one pass. Document both side by side, so the next owner sees the boundary rather than the pattern.

The failure signature: without the guard, the function returns None on an input that has a pair. Silent, not a crash. Detection is the assert itself (one O(n) pass, negligible against the O(n) scan) plus a property test against a brute-force oracle on random arrays of length ≤ 8. Cost of skipping it: a wrong answer that ships because the fixture happened to be sorted.

InputTwo pointersWhy
sorted valuesyesa move rules out a whole set of pairs
unsorted pair sumnonothing licenses discarding a side
non-negative subarray sumyes, sliding windowprefix sums monotone
subsequence, not subarraynoelements need not be adjacent

Keep the record next to the function, in the same file, so it moves with the code. Date it and name the language version the check was run against.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why loop termination and crossing delays a ship date?

Answer

What I'd say in the first two minutes

Lead with impact and a number, not the mechanism. Product can act on "1 in 400 queries on the affected shard return empty for a key that exists" and cannot act on "the loop condition is wrong." So:

"The search path has a boundary bug: for keys that sort to the end of a shard's range, it reports 'not found' instead of the value. It's about 1 in 400 queries on the affected shard. The fix is small but it touches a shared helper, so it's two days with tests, not two hours. We can ship Friday with a guard that hides the symptom, or Monday with the real fix."

Then stop. The number and the two options are the whole briefing; the mechanism is only there if they ask. (The figures here are illustrative: the point is that I'd bring measured ones.)

The mechanism, in one sentence

The search narrows a window with while lo < hi. That condition decides whether the pointers stop when they meet or after they cross; with < they stop on meeting, so when the window collapses to a single element the loop exits before comparing it, and a key that lands alone in the final window is reported missing.

Python
def find(a, target):          # a sorted ascending, inclusive bounds
    lo, hi = 0, len(a) - 1
    while lo < hi:            # exits when lo == hi
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1                 # the single-element window is never compared

Trace, a = [10, 20, 30, 40, 50], target = 50:

steplohimida[mid]action
10423030 < 50 → lo = 3
23434040 < 50 → lo = 4
344——4 < 4 false, exit
4————return -1

Index 4 holds 50. The answer is wrong, and it is wrong only for keys that end up alone in the final window.

Why it isn't a one-line change

The same while lo < hi appears in three call sites. Two of them compare once more after the loop, so they are correct; the third returns inside the loop and is not. Flipping the condition to <= in the shared helper fixes the third and breaks the other two, because they would then compare the final element twice. The real work is re-deriving the invariant, "the answer is always in [lo, hi] and is compared at least once", and adding the tests that pin it: empty input, single-element input, target at each boundary.

The options I'd put in front of them

optionship datecostrisk
Ship with a guard that falls back to a linear scan for the last bucketFriday~2 ms added on the affected pathmasks the bug; debt to repay
Delay for the real fix + regression matrixMonday2 daysnone beyond the delay
Ship behind a flag, fix next sprintFridayflag debtthe flag is the fix nobody schedules

How it escaped, and how we'd catch it

The happy-path inputs never land alone in the final window, so casual testing passes. The input distribution that exposes it is skewed keys: the ones that sort to the end of a range. Detection is a property test that compares the search against a linear scan over random sorted arrays, including length 0 and 1.

The deciding criterion

If the affected path is a small fraction of traffic and there's a fallback, ship with the guard and schedule the fix. If it's the primary path, or the "not found" result is silently cached, delay. That's the trade-off to state out loud; the mechanism is what makes the delay defensible rather than arbitrary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites proving linearity but cannot apply it?

Answer

The recitation is a proof of a conditional claim: the bound holds if each pointer moves monotonically. Application is knowing the condition and checking it. So I don't ask them to re-derive the proof: that tests recall. I change exactly one precondition, keep the surface of the problem familiar, and watch whether they reach for the condition or for the pattern.

Question 1: construct the counterexample. "Here's a two-pointer loop over a sorted array. Give me an input that makes it quadratic." A candidate who holds the mechanism points at the inner reset (lo = i + 1) and produces an input that triggers it. A candidate who holds the slogan says the loop is O(n) because "pointers only move forward", which is the exact claim under test.

Question 2: move the precondition. "Longest subarray with sum ≤ K. Does the standard sliding window work?" The window's correctness rests on the sum being monotone in the right pointer: extending can only raise it, shrinking can only lower it. Negative values break that. Ask for an input.

Take arr = [2, 2, -1], K = 3. The true answer is the whole array, length 3, sum 3. The window:

lo=0 sum=0 best=0
hi=0  sum=2  <=3  best=1
hi=1  sum=4  >3   shrink: sum-=arr[0]=2 -> sum=2, lo=1; best=max(1, 1)=1
hi=2  sum=1  <=3  best=max(1, 2)=2

It returns 2. The shrink at hi=1 discarded arr[0] and never reconsidered it, because the algorithm assumes a window that was too large stays too large. With a negative element the discarded prefix could have been part of a longer valid window. A candidate who produces this input and names the broken precondition, monotonicity of the window sum, has application, not recitation.

Question 3: locate the invariant. "State the invariant in one sentence, then give me the smallest edit that breaks it." For the two-pointer scan the invariant is that the pointers partition the search space and neither ever needs to revisit a discarded region. The smallest edit is any assignment that moves a pointer backwards. This separates candidates who can name the invariant from those who can only recite the bound.

AskIsolatesPass signal
"Give me an input that makes this loop quadratic"counterexample constructionpoints at the inner reset
"Does sliding window work for longest subarray sum ≤ K?"whether they check the preconditionnames monotonicity of the window sum
"State the invariant, then break it with one edit"whether they hold the mechanismnames the no-revisit invariant

What I'm listening for: they name the precondition before the pattern. The failure mode is a candidate who pattern-matches to "two pointers" and asserts O(n) without checking that the quantity being optimised is monotone. It survives casual testing because the happy path (sorted input, non-negative values) satisfies the precondition, so the bug only appears on the input distribution a quick check leaves out.

Alternatives I don't use: asking them to re-prove the bound (tests memory), or handing them a fresh hard problem (tests problem-solving, but confounds it with unfamiliarity). Changing one precondition isolates the transfer step, which is the thing in question.

Curated: · Written: · Reviewed:

Difficulty: Hard