Two Pointers pattern in detail: how to recognize and use it
The Two Pointers pattern one of the most common and famous patterns. It uses two indices or pointers to process data efficiently, with different variations for arrays, strings, and linked lists.
The Two Pointers pattern is a technique where two pointers are used to traverse a data structure instead of relying on nested loops. It is commonly used with arrays, strings, and linked lists and often reduces an O(n²) brute-force solution to O(n).
The main idea is simple: instead of checking every possible combination, two pointers move according to specific conditions and eliminate unnecessary candidates.
The main idea is:
instead of checking every possible combination, two pointers move according to specific conditions and eliminate unnecessary candidates.
How Two Pointers works
A pointer usually represents an index in an array or string:
int left = 0;
int right = nums.size() - 1;or a node in a linked list:
ListNode* slow = head;
ListNode* fast = head;Each pointer must have a specific role and movement rule.
There are three major variations of the Two Pointers pattern:
-- Opposite Directions
-- Same Direction
-- Fast and Slow Pointers
How to recognize the Two Pointers pattern
These are the most common approaches to recognizing the Two Pointers pattern during an interview. I'll discuss each approach in detail in the post about the three major variations of the Two Pointers pattern.
The problem involves pairs of elements - especially finding a pair with a target sum or optimizing a value based on two elements.
The input is sorted - sorted order lets us decide which pointer to move and safely eliminate candidates.
Elements need to be processed from both ends - common in palindrome checks, pair comparisons, or boundary-based problems.
The array/string must be modified in-place - removing duplicates, moving elements, or compressing data often suggests read/write pointers.
The problem involves a linked-list middle or cycle - this is a strong signal for Fast/Slow Pointers.
Two Pointers vs Sliding Window
These patterns are closely related but serve different purposes.
Two Pointers is the broader technique. The pointers can start at opposite ends, move independently, or move at different speeds.
Sliding Window normally represents a contiguous range. The pointers represent the boundaries of that window, which expands or shrinks while maintaining some condition.
