All Patterns

Two Pointers

Use two pointers moving through the data to find pairs, partitions, or solve problems on sorted arrays in O(n) time.

When to use

  • • Sorted array/string
  • • Finding pairs that sum to target
  • • Removing duplicates in-place
  • • Partitioning elements

When NOT to use

  • • Unsorted data without sorting first
  • • Need to track more than 2 positions

Common traps

  • • Forgetting to handle equal elements
  • • Pointer collision conditions
  • • Not sorting first when required

Key Invariant

Pointers narrow the search space by eliminating impossible candidates each step

Problems (12)

#4Move Zeroes
easyFREE
#10Remove Duplicates from Sorted Array
easyFREE
#24Merge Sorted Array
easyFREE
#62Squares of a Sorted Array
easy
#63Intersection of Two Arrays II
easy
#3Two Sum II - Input Array Is Sorted
mediumFREE
#273Sum
mediumFREE
#30Container With Most Water
mediumFREE
#229Find the Duplicate Number
medium
#230Sort Colors
medium
#2654Sum
medium
#117Trapping Rain Water
hard