Array techniquesAnimated
Two Pointer Technique
Move two indexes towards each other (or together) instead of nesting loops.
Time
O(n)
Extra space
O(1)
Use it for
Sorted arrays, pair sums, palindromes.
How it works
- The array must be sorted. Put one pointer at the start and one at the end.
- Add the two values. If the sum is too small, move the left pointer right (to a bigger value).
- If the sum is too big, move the right pointer left.
- If it matches, done. Each pointer only moves one way, so it takes O(n) instead of O(n²).
Watch it run
Loading animation…