Codacoda
Back to Academy

patterns

Two Pointers

The two pointers technique uses two references that traverse a data structure simultaneously, either from opposite ends moving inward or at different speeds (fast/slow). It reduces nested loops to a single pass, turning O(n²) brute-force solutions into O(n) linear scans on sorted or sequential data.

Use Cases

  • Finding pairs in a sorted array that sum to a target
  • Detecting cycles in a linked list with fast/slow pointers
  • Removing duplicates from a sorted array in-place

Complexity Analysis

MetricBestAverageWorst
TimeO(n)O(n)O(n)
SpaceO(1)

Visualization

13571113170123456
Target:18
Speed:1x
Array: [1, 3, 5, 7, 11, 13, 17]. Find two numbers that sum to 18.Step 1 / 7

Implementation

Output

Click "Run Code" to see output...