Same Direction
Both pointers move left to right, but at different speeds or conditions. The slow pointer tracks a position (like where to write), while the fast one scans ahead. Used in remove duplicates, partition problems.
How It Works
Same-direction pointers both sweep left to right but play different roles: a fast pointer reads every element, while a slow pointer marks the boundary of the processed or 'kept' region — typically the next write position. When the fast pointer finds an element worth keeping (not a duplicate, not a zero, satisfying the predicate), it writes that element at the slow pointer's slot and advances slow.
The payoff is in-place transformation without shifting. Naively deleting elements from an array costs O(n) per deletion for O(n²) total; the reader-writer sweep touches each element once, achieving O(n) time and O(1) extra space while preserving relative order of kept elements.
Step-by-Step Visualization
Code
static int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int slow = 0;
for (int fast = 1; fast < nums.length; fast++) {
if (nums[fast] != nums[slow]) {
slow++;
nums[slow] = nums[fast];
}
}
return slow + 1; // Length of unique portion
}
// Example: removeDuplicates(new int[]{1,1,2,2,3}) → 3, array becomes [1,2,3,...]Tips & Gotchas
Practice Problems
- 1Remove Duplicates from Sorted Array
- 2Move Zeroes
- 3Remove Element
- 4Sort Colors
About the Two Pointer Pattern
Use two index variables that move through the array strategically. They might start at opposite ends and converge, or both start at the beginning with one moving faster. This avoids nested loops.
When you see 'subarray', 'contiguous', or 'in-place', think arrays. The key is reducing brute-force O(n²) to O(n) using sliding window, two pointers, or prefix sums.
Common Array Interview Problems
- Two Sum
- Best Time to Buy & Sell Stock
- Maximum Subarray
- Merge Intervals
- Product of Array Except Self
- Container With Most Water
Frequently Asked Questions
How is this different from the fast and slow pointer cycle technique?
Same-direction pointers here differ in role, not speed rule: the fast one scans and the slow one writes, and both advance conditionally. Floyd's fast and slow pointers advance at fixed 1x and 2x speeds specifically to detect cycles or find midpoints.
Does the reader-writer pattern keep the array stable?
Yes for the kept elements — they are written in the order the reader encounters them, so their relative order is preserved. Elements past the writer's final position are leftover garbage and should be ignored or truncated based on the returned length.