IRInterview Ready
← All patterns

Two Pointers

Use two indices moving through a (usually sorted) sequence — toward each other, or at different speeds — to avoid nested loops.

When to use it

  • Searching for a pair/triplet in a sorted array satisfying a condition.
  • Comparing from both ends (palindrome checks, container/water problems).
  • In-place array partitioning or de-duplication.

Signals in the problem statement

  • Array or string is sorted (or can cheaply be sorted).
  • Asked for pairs/triplets summing to a target.
  • Need O(n) instead of an O(n²) brute-force nested loop.

Common pitfalls

  • Forgetting to skip duplicates when the problem asks for unique results (e.g. 3Sum).
  • Off-by-one errors when pointers cross (`while left < right` vs `<=`).

Practice Problems

Two Sum

Easy

Asked at: Amazon, Google, Meta

Given an array of integers `nums` and a target, return indices of the two numbers that add up to target.

Time: O(n) · Space: O(n)

3Sum

Medium

Asked at: Meta, Amazon, Microsoft

Given an array of integers, return all unique triplets that sum to zero.

Time: O(n^2) · Space: O(log n) to O(n) for sort

Trapping Rain Water

Hard

Asked at: Amazon, Google, Meta, Apple

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Time: O(n) · Space: O(1)