Builds onArrays and strings
01The idea
Two pointers means walking an array with two indices at once. Each step looks at the two items under the pointers, makes a decision, and moves one pointer. The pointers never move back, so the whole walk takes O(n), where a check of every pair would take O(n²).
There are two common layouts:
- Opposite ends. One pointer starts at the left end, the other at the right end, and they move toward each other until they meet. This works when the array is sorted, or when you compare the two ends of something, such as the two ends of a word.
- Same direction. Both pointers start at the left. A fast pointer reads every item, and a slow pointer marks where the next kept item goes. This works for filtering or compacting an array in place.
The question at each step is which item you can settle now. With opposite ends on a sorted array, one of the two end items is always the largest or smallest candidate left. You settle that item, and its pointer moves inward. Every step removes one item for good, so the walk ends after n steps.
02How to spot it
Two pointers fit when:
- the array is sorted, or sorting it first does not break the problem
- you need a pair, or the two ends of a range, that meets a condition such as a sum or a distance
- the problem says "in place" or "O(1) extra space", and you must remove or move items inside the same array
- you compare a string with its reverse, or the front of something with its back
Here is a good test. If you look at the two end items and can always rule out one of them, two pointers will work.
If the array is not sorted and order matters, you cannot rule out an end item, so two pointers do not apply. A hash map is the better tool there.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue