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.

Overview

Curated: · Written: · Reviewed:

Two Pointers

In one line

Two indices walk one sequence, converging from the ends, running in the same direction, or moving in lockstep at different speeds, so each move permanently discards candidates and the scan is O(n) instead of O(n^2). Reach for it when the input is sorted or has a positional order that lets one move rule out a whole class of answers.

Key definitions

  • Elimination argument: the reason a move is safe, namely that the candidates it discards can never be the answer.
  • Invariant: a statement of what the untouched region cannot contain. State it before writing the loop.
  • Converging pointers: lo starts at 0 and hi at n-1 on a sorted array, and they move toward each other.
  • Same-direction pointers: a read pointer that always advances and a write pointer that advances only when an element is kept.
  • Fast and slow pointers: one step versus two per iteration. A meeting proves a cycle exists but does not locate its entry.
  • Running maximum: the tallest wall seen so far from one side. Trapping-water uses it in place of the current height.

Formulas and complexity

T=O(nlog⁡n)+O(n)=O(nlog⁡n)T = O(n \log n) + O(n) = O(n \log n)

The sort dominates on unsorted input. The walk makes at most 2n2n pointer moves because neither pointer is ever assigned backwards. Extra space is O(1): two or three indices. A hash index for the same pair search needs O(n) memory. Fixing one element of a triple gives O(n2)O(n^2), not O(n3)O(n^3). Answering q sorted queries against m sorted elements by binary search costs O(qlog⁡m)O(q \log m); one merge walk costs O(q+m)O(q + m).

How it works

Converging pair search: if a[lo] + a[hi] is below the target, no pair using this lo can work with a smaller hi, so lo advances. If it is above, hi retreats. Each move deletes a row or column of the pair matrix.

Same-direction compaction: the read pointer moves every iteration and the write pointer moves only when the element is kept, so a[0:write] always holds the kept elements in order. Return the length. Elements past it are unspecified.

Cycle detection: inside a cycle the gap between fast and slow shrinks by one each step, so they meet. To find the entry, restart one pointer at the head and step both one at a time until they meet.

below above equal Sorted array with lo at 0 and hi at n-1 a lo plus a hi versus target lo + 1 discards pairs using this lo hi - 1 discards pairs using this hi Record, then skip equal values on both sides

When to use and when not to

SituationTwo pointersAlternative
Sorted values, pair or triple sumYes: O(n), or O(n^2) for triplesHash map if sorting is not allowed
Memory capped, streamed or memory-mapped dataYes: O(1) extraHash index needs O(n) memory
Unsorted inputNo, unless you pay for the sortHash map: O(n) time and space
One lookup in sorted dataOverkillBinary search: O(log n)
Many sorted queriesYes: one merge walkRepeated binary search
Original indices must be reportedSort carrying indices, or use a hash mapHash map keeps positions

Traps interviewers probe

  1. Running the sorted walk on unsorted input. Fix: sort with original indices or use a hash map, and quote the sort cost.
  2. Moving both pointers on a mismatch, which skips valid pairs. Fix: advance only the pointer the inequality implicates.
  3. Leaving duplicates after a match, so results repeat or blow up on runs of equal values. Fix: skip equal values at lo and hi at the point of advancing.
  4. Treating Floyd's meeting point as the cycle entry. Fix: run the second phase one step at a time from the head.
  5. Off-by-one loops. Use lo < hi when a single element is not admissible and lo <= hi when it is. For the middle of an even list, while fast and fast.next returns the second middle and while fast.next and fast.next.next returns the first.

Interview tips

Open by naming the ordering and the invariant in one sentence, then give the complexity with the sort included.

Follow-ups to expect: why not hashing (memory, and whether output must be ordered); why the merge uses <= (stability); why in-place partition loses relative order (the swap moves an element across the others); why container-with-most-water always moves the shorter side (area is bounded by the shorter side and the width only shrinks); why trapping-water uses running maxima (the other side is already known to be at least as tall); why sorting mutates a caller's list (use sorted when mutation is outside the contract); why the Dutch-flag mid pointer stays put after a swap with high (the element just brought in is unexamined).

30-second answer: "The input is sorted, so each move discards a whole row of the pair matrix. When the sum is below target, only a larger left value can help, so lo advances. That is two indices and constant extra space. The sort costs O(n log n), so the total is O(n log n). The walk itself is linear because each pointer only moves one way, at most 2n moves. I skip duplicates as I advance. If the input were unsorted, I would use a hash map instead."

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.