Skip to Content

When does the two-pointer pattern beat hash-map lookups?

Category: DSA Patterns

Answer

Two pointers works on sorted arrays/strings where you walk inward from both ends to find pairs, triplets, or palindromes in O(N). A hashmap also gives O(N) but with O(N) memory. Two-pointer is preferred when memory is tight or when the array is sorted (e.g., “two sum in a sorted array”).

Concrete examples from the fca project context

Example 1

Two sum sorted: left=0, right=n-1; if sum > target right—; if sum < target left++.

Example 2

Three sum: sort first, fix one i and two-pointer the rest, skip duplicates.

Example 3

Container with most water: maximize area(left, right) * (right-left) greedily.

Data flow / flow chart

sorted arr [a..b..c..z]               
  L->                          <-R                                      result

Takeaway

Two pointers when the array is sorted and O(1) extra space matters.