Skip to the solution
MediumDSA8 min read

What is the two-pointer technique?

193 views

The problem

Question presented to candidate: "Explain the two-pointer technique. Then, in Python, use it to find two numbers in a sorted list that add up to a target, and tell me how it beats the obvious nested loop."

What a strong answer should cover:

  • Two indices moving through the data under a rule; the two shapes (converging from both ends, and same-direction read/write).
  • Why moving a pointer is safe: the sorted (monotonic) order lets one comparison rule out a whole element.
  • O(n) time and O(1) extra space versus O(nยฒ) for checking every pair; sorting first adds O(n log n).
  • When a hash map is the better tool (unsorted input, original indices needed).
  • Python specifics: tuple swap a[i], a[j] = a[j], a[i], len(arr) - 1 is -1 for an empty list so the loop simply does not run, and avoiding slices like arr[1:] inside the loop because each one copies.

Clarifying questions expected:

  • "Is the list sorted, and can it contain duplicates or negative numbers?"
  • "Should I return indices or values, and what if no pair exists?"

Code / implementation expected: Yes โ€” a Python pair_sum(arr, target) with left/right indices, plus a same-direction example such as removing duplicates in place.

  • two-pointers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read ยท 9 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonPair sum with converging pointers, and a count of checks vs brute force
PythonSame-direction pointers: remove duplicates and reverse in place

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 116 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Find median from data stream with two heaps โ€” invariant and rebalancing?

Continue