Skip to main content

Pattern · 20 problems

Two Pointers Interview Problems

Two indexes beat a nested loop when the input has order or symmetry. Every move has to rule something out for good.

Get the link for your laptop

Free: write the code and run it, no sign-up.

When I reach for it

  • The array is sorted, or you can sort it.
  • You need a pair, a triple or a palindrome.
  • You shrink from both ends, or one index chases another.

Problems, easiest first

5 easy · 13 medium · 2 hard. Open one to read it, then write it in the free editor.

The idea

Each pointer move must throw away options that cannot win. If you cannot say what a move rules out, the pointers are wandering.

Opposite ends work when order tells you which side to move. Same-direction pointers work when one index reads and the other writes.

left, right = 0, len(nums) - 1
while left < right:
    total = nums[left] + nums[right]
    if total == target:
        return [left, right]
    if total < target:
        left += 1      # too small: only a bigger left can help
    else:
        right -= 1     # too big: only a smaller right can help
Compare the two ends, then move the side that cannot help. Order is what makes each move safe. Python shown; the idea carries to every language in the editor.

Where it goes wrong

  • Moving the wrong pointer. Say why the move is safe before you make it.
  • Forgetting that the array has to be sorted for opposite-end pointers.
  • Counting duplicates twice in three-sum style problems.

Say this before you type. Say what each pointer means and what a move to the left or right rules out.

Where Coco comes in

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit, and to talk with her for one hour. After that, talking comes with the $79 pack. Anyone can open the editor and run their code.

Questions people ask

How is two pointers different from a sliding window?
Two pointers reads the values at each index. A window tracks everything between them, such as a sum or a count.
Does the array have to be sorted?
For opposite-end pointers, yes. Same-direction pointers, like removing duplicates in place, work on any order the problem gives you.

Meet these next

Fin and Coco are characters, not people. strongyes.io is independent. Leo builds it with AI agents.