The Two-Pointer Technique is an algorithmic pattern that uses two pointer indices to coordinate searches or mutations across an array or sequence. By moving pointers intelligently based on problem constraints, two-pointer algorithms reduce brute-force $O(n^2)$ quadratic nested loops into blazing $O(n)$ linear time with $O(1)$ auxiliary space.
Imagine inspecting whether a word like "RADAR" is a palindrome:
'R' and your right index finger on the last letter 'R'.left starts at index 0.right starts at index n - 1.left++, right--) until they meet.slow tracks the boundary of clean/valid data.fast scans forward through the array.Given a 1-indexed array of integers numbers sorted in non-decreasing order, find two numbers such that they add up to a specific target number:
Remove duplicates in-place such that each unique element appears only once, returning the count of unique items.
nums = [1, 1, 2, 2, 3]read_idx (Fast) | Current Value | Previous Value | Is Unique? | Action | Modified Array |
|---|---|---|---|---|---|
| 1 | 1 | 1 | No | Skip | [1, 1, 2, 2, 3] |
| 2 | 2 | 1 | Yes | nums[1] = 2, write++ | [1, 2, 2, 2, 3] |
| 3 | 2 | 2 | No | Skip | [1, 2, 2, 2, 3] |
| 4 | 3 | 2 | Yes | nums[2] = 3, write++ | [1, 2, 3, 2, 3] |
Result: First 3 elements are [1, 2, 3]. Return length 3 in $O(n)$ time with $O(1)$ space!
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.