Data Structures & Algorithms practice
Data Structures & Algorithms · Array Patterns

Two Pointers: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1The Pattern NamedEasyMust Do

Define what a "two-pointer" solution is, and give the argument that makes it O(n). Show a movement counter that proves the bound on real input.

Q2The Three FamiliesEasy

There are three shapes of two-pointer solution. Name them, say what question each one answers, and give a one-line example of each.

Q3The Brute-Force BaselineEasy

Write the nested-loop version of "find two values summing to a target" and count its operations. State precisely what has to be true about a problem before two pointers can beat it.

Q4The Elimination ArgumentEasyMust Do

On a sorted list, find two values summing exactly to a target in O(n). Prove that discarding a pointer's value is safe — do not just assert it.

Q5The Proof TemplateEasy

Turn the elimination argument into a reusable four-line template, and apply it to a second problem to show it generalises.

Q6The Sorted PreconditionEasy

Run the pair-sum two-pointer on unsorted input. Show that it does not raise, does not loop forever, and simply returns the wrong answer — then say why that is the dangerous failure mode.

Q7Counting Pairs With A SumMedium

Count all pairs of indices in a sorted list whose values sum to a target — including duplicates. Getting the duplicate arithmetic right is the whole question.

Q8Counting Below A ThresholdEasy

Count pairs whose sum is strictly less than a target, in O(n). The trick is that one comparison settles many pairs at once.

Q9Closest Pair SumEasy

Find the pair whose sum is closest to a target — no exact match required. Show why the same elimination rule still applies when there is no hit to stop on.

Q10Walking Two SequencesEasyMust Do

Decide whether one string is a subsequence of another using two same-direction pointers. Prove that skipping a non-matching character in the haystack can never lose a match.

Q11Repeated Subsequence QueriesMedium

You must answer "is this a subsequence?" for thousands of different needles against one fixed haystack. Show why the O(n) walk is now the wrong shape, and what changes.

Q12The Gap PointerEasy

Find the k-th element from the end of a sequence in a single pass, without knowing the length in advance. Two pointers held a fixed distance apart is its own idiom.

Q13The Midpoint In One PassEasy

Find the middle element in one pass with a fast pointer and a slow pointer. State the convention you pick for even lengths and make the code match it.

Q14Why 2:1 MeetsEasyMust Do

A slow pointer takes one step, a fast pointer takes two. Prove that if the walk ever enters a cycle, the two must eventually land on the same position — and that the proof needs the ratio to be exactly 2:1 to be this simple.

Q15Floyd On An Index ChainEasy

An array of n values in the range 0..n-1 defines a walk: from index i, go to index values[i]. Detect whether that walk ever revisits a position, in O(1) space.

Q16Finding The Cycle EntranceMediumMust Do

The two pointers have met somewhere inside the cycle. Find where the cycle begins, and prove the two-line trick that does it.

Q17Find The Duplicate NumberMedium

An array of n + 1 integers, each between 1 and n, must contain a repeat. Find it without modifying the array and in O(1) extra space.

Q18Cycle LengthEasy

Once the pointers have met, measure the length of the cycle. Then report the tail length too, and check both against a direct count.

Q19Brent's AlgorithmMedium

Floyd's is not the only O(1)-space cycle finder. Implement Brent's algorithm — the "teleporting tortoise" — and count how many times each one reads the data.

Q20Palindromes By ConvergenceEasyMust Do

Check whether a string is a palindrome with converging pointers. Then extend it to ignore case and non-alphanumeric characters, without building a cleaned copy of the string.

Q21Palindrome After One DeletionEasy

Decide whether a string can be made a palindrome by deleting at most one character. There is exactly one place where the walk has to branch — find it and justify why one branch level is enough.

Q22Which Pointer MovesEasyMust Do

Write the checklist you run before choosing which pointer to move, and apply it to four problems that each answer it differently.

Q23When Two Pointers Is WrongEasy

Give two problems where a two-pointer solution looks natural and is provably incorrect. Show the failure and name the property that is missing.

Q24The Invariant CommentEasy

Every two-pointer loop should carry a one-line invariant in a comment. Write the invariant for three loops, then break one deliberately and show the invariant catching it.

Q25The Six ShapesEasyMust Do

Build the decision table for this topic: given a problem statement, which two-pointer shape does it reduce to? Include the cases where the answer is "none of them".

Q26Three-SumMediumMust Do

Find all distinct triplets summing to zero. Write the O(n^3) version first, state its cost, then reduce it to O(n^2) by fixing one value and running a two-pointer walk on the rest.

Q27The Duplicate GuardsMedium

Three-sum has three separate duplicate-skipping guards. Name each one, show the exact wrong output you get when it is missing, and explain why they cannot be replaced by a single set() at the end.

Q28Three-Sum ClosestMedium

Find the triplet whose sum is nearest a target. Explain why the early break that three-sum-to-zero uses is not available here.

Q29Three-Sum SmallerMedium

Count the triplets whose sum is strictly less than a target. Reuse the "count many pairs at once" step and state the new complexity.

Q30Four-SumMedium

Extend the pattern to four values summing to a target. Add the two pruning tests that keep it usable, and state the complexity.

Q31k-Sum By NestingMedium

Write a k_sum that works for any k >= 2, without recursion, and say honestly what that costs you in clarity.

Q32Sorted Versus MappedEasy

Two-sum on unsorted input has two good solutions. Implement both, state the trade, and say which one the problem statement chooses for you.

Q33Container With Most WaterMediumMust Do

Given wall heights, find the two walls holding the most water. Prove that moving the shorter wall inwards can never discard the best answer.

Q34Moving The Taller SideEasy

Change the container solution to move the taller wall instead, and find an input where it gives the wrong answer. Explain the failure in terms of the proof.

Q35The Equal-Height CaseEasy

When the two walls are exactly equal, which one should move? Show that moving either is safe, and that moving both is also safe — then say why you should still move only one.

Q36Trapping Rain Water, NaivelyMedium

Compute how much water a skyline traps, the obvious way: for each column, look left and look right. State the cost and show it growing.

Q37Rain Water With Two ScansMedium

Remove the quadratic factor with two precomputed running-maximum arrays. State the new time and space, and confirm both against the naive version.

Q38Rain Water In O(1) SpaceMediumMust Do

Now do it with two pointers and no auxiliary arrays. The proof is the interesting part: explain why the shorter side's answer is already fully determined.

Q39The Wrong Rain-Water WalkMedium

Write the rain-water two-pointer with height[lo] <= height[hi] replaced by a comparison of left_max and right_max, and decide by experiment whether it is a bug or an equivalent formulation. Then explain the result.

Q40Backspace String CompareMediumMust Do

Two strings contain # meaning "backspace". Decide whether they are equal after applying the deletions, using O(1) extra space. Explain why the walk must go right to left.

Q41Squares Of A Sorted ArrayEasy

A sorted array may contain negatives, so squaring it destroys the order. Restore sorted order in O(n) with two pointers.

Q42Filling From The FrontEasy

Try to write the sorted-squares walk filling the output from index 0 upwards. Show what goes wrong and state the rule it teaches.

Q43MountainsMedium

Validate that a sequence strictly rises then strictly falls, and find the longest such run inside a larger sequence. The pointers here move outwards from a candidate peak.

Q44Expanding Around A CentreMediumMust Do

Find the longest palindromic substring by expanding outwards from every possible centre. Explain why there are 2n-1 centres and not n.

Q45Counting Palindromic SubstringsMedium

Count every palindromic substring, counting different positions separately. Reuse the centre expansion and show why the count comes out of the loop for free.

Q46Reversing WordsMedium

Reverse the order of words in a character list, in place, using only converging pointers. Handle multiple spaces, and state why the two-step method works.

Q47The Shortest Unsorted WindowMedium

Find the shortest subarray that, if sorted, would sort the whole array. Solve it with two scans that move in opposite directions, and prove each boundary is where you claim.

Q48Boundary By SortingMedium

Solve the same problem by sorting a copy and comparing element by element. Compare the two approaches on correctness, cost and clarity, and say which you would ship.

Q49Intersecting Interval ListsMediumMust Do

Two lists of disjoint, sorted intervals. Produce every overlap between them with a same-direction walk, and prove that advancing the list with the smaller end point is safe.

Q50From Statement To ShapeMedium

Build a classifier: given a problem statement in words, decide which of the six shapes applies, or that none does. Test it on fifteen statements and report where it is uncertain.

Q51Triplets Under Heavy DuplicationHard

An array where only five distinct values appear, repeated thousands of times. Count distinct value-triplets summing to zero, and show that the guarded walk is already fast — then show the counting version that ignores the walk entirely.

Q52The Staircase WalkMediumMust Do

A matrix whose rows are sorted left to right and whose columns are sorted top to bottom. Find a value in O(rows + cols) with two pointers, and prove that each step eliminates a whole row or a whole column.

Q53Choosing The CornerMedium

Try the staircase walk from each of the four corners. Show that two of them work and two are stuck, and state the property that separates them.

Q54Pairs With A Given DifferenceMedium

Count pairs whose values differ by exactly k. Both pointers move in the same direction here — explain why converging pointers is the wrong shape for a difference.

Q55Pairing Under A LimitHard

People must be carried two at a time, and no boat may exceed a weight limit. A rule is proposed: repeatedly pair the heaviest with the lightest that fits. Test that rule exhaustively on small inputs rather than trusting it.

Q56Merging From The BackMedium

Array A has room at the end for all of array B. Merge B into A in place. Explain precisely why the write pointer must start at the end.

Q57Trimming Common EndsMedium

Two strings share a prefix and a suffix. Trim both with converging pointers, and use the result to answer "do these differ by exactly one contiguous edit?"

Q58Intersecting Three SequencesMedium

Find the values present in all three sorted arrays with a single pass. Show that the rule "advance whichever pointer holds the smallest value" is what makes it linear.

Q59One Edit ApartMedium

Decide whether two strings differ by exactly one insertion, deletion or replacement, in O(n) time and O(1) space. Enumerate the cases before writing the code.

Q60Counting TrianglesHardMust Do

Count the triples of side lengths that can form a triangle. Fix the largest side and walk the rest — and explain why fixing the largest is what makes one comparison enough.

Q61Closest Across Two ArraysMedium

Given two sorted arrays, find the pair — one value from each — whose difference is smallest. Both pointers move forwards; say which one and why.

Q62Matching Two Sorted ListsHard

Assign resources of given capacities to requests of given sizes, one each, maximising the number of requests served. Implement the walk, then verify the rule against an exhaustive optimum.

Q63Best Pair Sum Across Two ArraysHard

Two sorted arrays. Find the pair, one from each, whose sum is closest to a target. State the movement rule and prove it, then handle the case where several pairs tie.

Q64Reversing Only What MatchesMedium

Reverse only the characters that satisfy a predicate, leaving everything else in place. Show the skipping walk and the invariant that keeps it linear.

Q65Sorting A Transformed ArrayHardMust Do

Apply f(x) = A*x*x + B*x + C to every value of a sorted array and return the results in sorted order, in O(n). The shape of the parabola is what makes it possible.

Q66Longest Word By DeletionHardMust Do

Given a string and a dictionary, find the longest dictionary word obtainable by deleting characters from the string. Use the subsequence walk, then measure how much a precomputed index helps.

Q67Counting Subsequences By ExtremesHard

Count the subsequences whose smallest plus largest element is at most a target. The walk counts an exponential number of subsequences without enumerating any of them.

Q68Triples With MultiplicityHard

Count ordered index triples summing to a target, where equal values at different positions count separately. Get the three duplicate cases right, and prove each formula.

Q69When The Sort DominatesHard

Several problems in this topic begin with sorted(values). Measure when that sort is the whole cost, and find the input sizes where an O(n) hash-based solution wins outright.

Q70Choosing The TechniqueMediumMust Do

Build the full decision procedure for this topic: four questions that route a problem to two pointers, to a different technique, or to brute force. Run it on ten problems and show its reasoning.

Q71The Unsorted-Input TrapHard

A function sorts its input, walks it, and returns indices. It passes every test. Find the bug, and write the test that would have caught it.

Q72Skipping In The Wrong PlaceHard

Three-sum's duplicate skip can be placed before recording a triplet or after. One placement is correct. Determine which by experiment and explain the difference.

Q73The Loop That Never EndsHard

Write three two-pointer loops that hang, each for a different reason. Add the one assertion that catches all three, and measure what it costs.

Q74Strict Or NotHard

while lo < hi and while lo <= hi are not interchangeable. Give a problem that needs each, show the failure when they are swapped, and state the rule.

Q75Using One Element TwiceHard

The "same index twice" bug appears in more places than the loop bound. Find three of them and write the single check that detects all three.

Q76The Overflow Python HidesHard

values[lo] + values[hi] cannot overflow in Python. Show exactly where it would in C or Java, simulate the wrap, and say what a correct implementation looks like in those languages.

Q77Moving The Wrong PointerHardMust Do

Four implementations of "the largest area between two walls" — the same loop with a different move rule. Decide which ones are correct without reading the code, then explain every failure, and every apparent success.

Q78When Elimination Is FalseHard

Construct a problem where the two-pointer code is well formed, terminates, and is wrong on most inputs — because the elimination step assumes something the data does not provide. Then find the smallest counter-example automatically.

Q79A Step Of ThreeHard

Replace the fast pointer's two-step with a three-step in cycle detection. Determine experimentally when it still works and when it does not, then explain the arithmetic.

Q80The Hidden PreconditionHard

"Find the duplicate number" with Floyd's algorithm relies on three preconditions. Break each one and show a different failure — a crash, a wrong answer and an infinite loop.

Q81Mutating While WalkingHardMust Do

A two-pointer loop that modifies the sequence it is walking. Show three distinct ways it goes wrong, and give the two safe patterns.

Q82The Even-Length CentreHard

Centre expansion has an off-by-one that only shows on even-length answers. Produce it, then write the property test that would have caught it on the first run.

Q83Indices Are Not CharactersHard

A palindrome checker walks a string by index. Show three kinds of text where "index" and "character the reader sees" are different things, and say what each one costs you.

Q84The O(n) That Is NotHardMust Do

Four two-pointer loops that look linear. Two of them are quadratic. Identify which by measuring, then name the operation responsible in each.

Q85The Suite That Catches All Of ItHard

Build one test harness that would have caught every bug in this band. It must work without a reference implementation wherever possible, and it must minimise its counter-examples.

Q86The Pointer TracerMini-ProjectMust Do

Build a tracer that records every pointer move a walk makes and renders the walk as ASCII frames, with the eliminated region shaded. Use it on three different problems.

Q87The Differential FuzzerMini-Project

Build a reusable fuzzer: it generates inputs, compares a candidate against a reference, shrinks any counter-example to a minimum, and reports coverage of the input space it explored.

Q88The Palindrome ToolkitMini-Project

Build a small library around centre expansion: longest palindrome, count of all palindromes, all maximal palindromes, and the check for "palindrome after one deletion". Share one expansion primitive between all four.

Q89The k-Sum ServiceMini-Project

Build a solver that answers k-sum for any k, reports the number of inner steps it took, and refuses work it cannot finish in a stated budget. Show the step counts growing with k.

Q90Duplicate Finder On A ChainMini-ProjectMust Do

Build a duplicate detector for a large read-only sequence of ids, using the fast/slow walk. Benchmark it against a set, and report honestly which one you would ship.

Q91The Near-Duplicate MatcherMini-Project

Build a tool that decides whether two records are "the same thing typed slightly differently". Combine common-prefix/suffix trimming, the one-edit walk and the subsequence walk, and report which rule fired.

Q92The Rain-Water VisualiserMini-Project

Render a skyline and the water it traps as ASCII, then animate the two-pointer walk filling it in. Verify the picture against the computed total.

Q93The Two-Log ReconcilerMini-Project

Two sorted event logs must be reconciled: what is in both, what is only in one, and where they disagree on a value. Walk them once, and handle duplicate timestamps explicitly.

Q94The Crossover BenchmarkMini-Project

Build a benchmark harness that finds the input size at which one algorithm overtakes another, and use it on three pairs from this topic. Report the crossover, not just the winner.

Q95The Technique AdviserMini-Project

Build a tool that takes a problem description plus a few structured facts and returns a recommended technique, the elimination argument to prove, and the test that should be written first. Run it on enough problems to exercise every branch.

Q96Explaining It ColdInterview

An interviewer asks: "What is the two-pointer technique, and when does it apply?" Write the ninety-second answer, then the follow-up answers to the three questions that always come next.

Q97Diagnosing By ReasoningInterview

You are handed a three-sum implementation that returns duplicates on some inputs. Find the bug by reasoning about the invariants first; only then confirm it with a test. Show both halves of the work.

Q98Designing For QueriesInterview

Design a service that answers "which two of my values sum closest to X?" for many different X, over a dataset that occasionally changes. State what you would build for three different read/write mixes, and be explicit about what each one gives up.

Q99The Mock InterviewInterview

A transcribed interview on container-with-most-water, where the interviewer refuses to accept the algorithm until the candidate proves it. Follow the exchange and note where the proof actually gets made.

Q100CapstoneInterviewMust Do

The capstone. Take four problems from this topic, and for each one: implement it, state the elimination argument as executable documentation, prove it holds by exhaustive differential test, measure the complexity class from timings, and produce a report that fails loudly if any claim is unsupported.

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session