Two Pointers Tecnique - rFronteddu/general_wiki GitHub Wiki
Typical problems
- Reverse String / Array (In-Place)
- Pair With Target Sum (Sorted Array)
- Remove Duplicates I
- Remove Duplicates II
- Container With Most Water
- Valid Palindrome memorize regex in c++ and java
- Squares of a Sorted Array
- 3Sum
- Trapping Rain Water
- Linked List Cycle I
- Linked List Cycle II - once they meet, just advance by one, floyd hare algorithm
- Find the Duplicate Number
- Determine if a number is happy ** can you see the problem as a cycle detection?
- Move Zeroes - Slow–fast (in-place compaction)
- Remove Element - Slow–fast (filter in-place)
- Sort Colors - 3 pointers (low, mid, high)
- Is Subsequence - Two forward pointers
- Partition Labels - Expanding right boundary
- 4Sum - Sort + nested + two pointers
- Intersection of Two Arrays II - Sort + merge-like pointers
- Backspace String Compare - Reverse two pointers
- Next Permutation - Two pointers + reverse suffix
Lists and Cycles => O(n)
A classic problem is to detect if there are cycles in a list. Imagine two runners. If they are running on a circular path, a faster runner will reach the slower one (see the tortoise and hare math). To detect the node that starts the cycle, first you use the 2PT to detect if there is a cycle, then reset the slow pointer and advance both 1 step at a time until they meet again.
2PT In Linked List Template
ListNode slow = head;
ListNode fast head;
// change condition to fit problem
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // fit to problem
return true;
}
}
return false; // fit to problem
Tips:
- O(n+m) = O(n) where m<n is the number of steps to catch up before the two pointers meet if there are cycles.
Example: Reverse Array
2PT II
You can also use two pointers that move at different speed.
Example: Remove element from array in place, return new len
Intro
Use the two pointers technique when:
- The input is a sorted array or can be sorted.
- You’re looking for:
- Pairs or subarrays with a condition (sum, difference, etc.).
- In-place modifications (no extra space).
- Window-like problems where ends move toward each other.
- You need to reduce O(n²) brute force to O(n).
Typical pointer setups:
- left at start, right at end
- or slow and fast pointers
Ask yourself:
- Is the array sorted or sortable?
- Do I need:
- Pairs?
- In-place updates?
- Min/max distance or area?
- Can I move one pointer to improve the condition?
If yes → Two pointers is a strong candidate.