Two Pointers Pattern
The Two Pointers technique involves using two pointers to iterate through an array or list simultaneously. This pattern is particularly effective for problems involving sorted arrays, palindromes, or finding pairs that meet specific criteria.
When to Use This Pattern
- When dealing with sorted arrays or lists
- When you need to find pairs of elements that satisfy a condition
- When working with palindromes or symmetric structures
- When you need to merge two sorted arrays
- When removing duplicates from sorted arrays
Key Concepts
There are two main variations of the two pointers technique:
Visual Representation
Two Pointers Technique - Opposite Ends
1. Opposite Ends (Converging Pointers)
Start with one pointer at the beginning and one at the end, then move them toward each other:
left = 0
right = n - 1
while left < right:
# Process elements at left and right
if condition:
left += 1
else:
right -= 1
2. Same Direction (Fast and Slow)
Both pointers start at the beginning, but move at different speeds:
slow = 0
fast = 0
while fast < n:
# Process elements
if condition:
# Move slow pointer
slow += 1
fast += 1
Time Complexity
Two pointers typically reduces time complexity from \(O(n^2)\) to \(O(n)\) by eliminating the need for nested loops.
Visual Simulation: Two Sum in Sorted Array
Let's trace through finding two numbers that sum to target = 9 in array [2, 7, 11, 15]:
Initial State:
Array: [2, 7, 11, 15]
left = 0, right = 3, target = 9
Iteration 1:
nums[left] + nums[right] = 2 + 15 = 17
17 > 9, so move right pointer left (need smaller sum)
left = 0, right = 2
Iteration 2:
nums[left] + nums[right] = 2 + 11 = 13
13 > 9, so move right pointer left
left = 0, right = 1
Iteration 3:
nums[left] + nums[right] = 2 + 7 = 9
9 == 9, found! Return [0, 1]