Two Pointers
The two pointers technique helps us solve problems by performing actions on the values located at the pointers or deriving new information based on them.
Overview
A variable that references a specific position or item in a linear data structure is called a pointer. The two pointers technique helps us solve problems by performing actions on the values located at the pointers or deriving new information based on them.
Pointer
The Technique
The basic foundation of the two pointers technique is as follows:
Define Pointers
Specify the variable names and values they reference in the data structure.
Perform an Action
Do something that gets you closer to the goal at hand. For example, swap values at the two pointers, calculate a value, etc.
Move Pointers
Move one or both pointers. Pointers may move independently, in opposite directions, and/or at different "speeds".
Check a Condition
Perform a conditional check to determine if the steps should end or return to Step 2.
With this foundation, we typically employ the technique in two different ways:
- Contrary Motion - the two pointers move toward one another
- Similar Motion - the two pointers move in the same direction
Contrary Motion
In contrary motion, pointers move toward one another. This implies that our pointers start at opposite ends of the data structure. For this reason, we commonly name
- a variable
left
that points to the first item in the data structure and - a variable
right
that points to the last item
Example
Let's say we wanted to reverse our nums
array. To accomplish this, we can devise a two pointers-based algorithm with contrary motion pointers.
The pointer movement described by our pseudocode would look something like this.
Here's a sample implementation: