Two Pointer Techniques
# CHAPTER 5
Two Pointer Techniques
1. Chapter Introduction
In Chapter 4, we used Hash Maps to optimize our algorithms, which required O(N) auxiliary Space. What if the interviewer says: *"Great, you solved it in O(N) Time. Now, can you solve it in O(1) Constant Space?"* You cannot use a Hash Map. You cannot create a new array. You must manipulate the input strictly in-place. Enter the Two Pointer technique. This chapter covers the two main variations: Opposite-End Pointers (for sorted arrays and palindromes) and Fast/Slow Pointers (for linked lists and cycle detection).2. What is the Two Pointer Technique?
Instead of iterating through an array with a singlefor loop variable i, we use two integer variables (left and right, or fast and slow) that represent array indices. We move them based on specific logical conditions.
Because we are only creating two integer variables, the Space Complexity is strictly O(1).
3. Pattern 1: Opposite-End Pointers (The Convergence)
This pattern places one pointer at index 0, and one pointer at the last index. They move towards the center until they meet. *Prerequisite:* This is almost always used on Sorted Arrays or Strings.*Example: Two Sum II (Input Array is Sorted)*
*Prompt:* Find two numbers that add up to target. The array is sorted. Do not use extra space.
*The Logic:* Because the array is sorted, moving left increases the sum. Moving right decreases the sum. We logically hone in on the target without checking every combination.
4. Pattern 2: Fast and Slow Pointers (The Tortoise and Hare)
This pattern uses two pointers starting at the *same* location, but they move at different speeds.Fast moves two steps at a time. Slow moves one step at a time.
*Use Cases:* Linked Lists, finding the middle of an array, detecting cycles.
*Example: Remove Duplicates from Sorted Array (In-Place)* *Prompt:* Remove duplicates so each unique element appears only once. Return the new length.
5. Pattern 3: Three Pointers (Sorting Colors)
Sometimes, an interview asks you to sort an array containing only a few distinct values (e.g., 0s, 1s, and 2s) in O(N) time. You cannot use standard sorting (O(N log N)). *The Dutch National Flag Algorithm:* Use three pointers:low, mid, and high.
-
Move
midacross the array.
-
If it sees a 0, swap it with
low(push 0s to the front).
-
If it sees a 2, swap it with
high(push 2s to the back).
- If it sees a 1, leave it in the middle.
6. Real-World Scenario: Container With Most Water
*Prompt:* Given an array of heights[1,8,6,2,5,4,8,3,7], representing vertical lines, find two lines that together with the x-axis form a container that holds the most water.
*The Two Pointer Logic:*
-
Place
leftat 0,rightat the end.
- The volume of water is limited by the *shorter* line.
- Calculate the area.
- *The Move:* To potentially find a larger area, you MUST move the pointer pointing to the *shorter* line inward. Moving the taller line cannot possibly increase the height of the container.
-
Repeat until
left >= right.
7. Mini Project: Reverse a String In-Place
Strings in Python/Java are immutable, so imagine the input is an array of characters:['h','e','l','l','o'].
Write the Two Pointer algorithm to reverse it in O(1) space.
-
1.
left = 0,right = length - 1.
-
2.
While
left < right:
-
3.
Swap
arr[left]andarr[right].
-
4.
left++,right--.
8. Common Mistakes
-
Infinite Loops: Forgetting to explicitly increment/decrement the pointers inside the
whileloop, causing the program to freeze.
-
Incorrect
whileCondition: Usingwhile left <= rightwhen you shouldn't. Ifleft == right, they are pointing to the exact same element. If the problem requires *two distinct* elements, the condition MUST bewhile left < right.
9. Best Practices
-
In-Place Swapping: In Python, you can swap values elegantly in one line without a temporary variable:
nums[left], nums[right] = nums[right], nums[left].
10. Exercises
-
1.
If you use Fast (moves 2 steps) and Slow (moves 1 step) pointers on a Linked List, what happens when
Fastreaches the end of the list? Where isSlow?
- 2. Why does the Opposite-End pointer technique (Two Sum II) fail if the array is NOT sorted?
11. MCQs
What is the primary architectural goal of using the Two Pointer technique?
The "Opposite-End Pointers" pattern (one at index 0, one at the last index) relies heavily on what prerequisite?
In the Two Sum II (Sorted Array) problem, what happens when current_sum > target?
What is the standard while loop condition for Opposite-End pointers requiring two *distinct* elements?
How do the pointers behave in the "Fast and Slow Pointers" (Tortoise and Hare) pattern?
When removing duplicates from a sorted array in-place, what is the role of the Slow pointer?
In the "Container With Most Water" problem, why do you always move the pointer pointing to the *shorter* line inward?
What is a common pitfall that causes an Infinite Loop when implementing Two Pointers?
If a Fast pointer moves 2 steps and a Slow pointer moves 1 step through an array, where is the Slow pointer when the Fast pointer reaches the very end?
Can you use Opposite-End pointers on an Unsorted array to find a target sum in O(N) time?
14. Interview Questions
- Q: "Given an array of integers, move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array." (LeetCode 283).
15. FAQs
- Q: If a problem says "Given a sorted array...", should I automatically think of Two Pointers?
16. Summary
The Two Pointer technique is the master key for achieving O(1) Space Complexity. When faced with a sorted array or a palindrome, use Opposite-End Pointers converging on the center. When modifying an array in-place or detecting cycles, use Fast and Slow Pointers starting from the same side. Always remember to check yourwhile loop conditions to prevent infinite loops, and ensure you explicitly move your pointers based on logical deductions.