Skip to main content
LeetCode Prep
CHAPTER 05 Beginner

Two Pointer Techniques

Updated: May 18, 2026
5 min read

# 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 single for 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.

python
123456789101112131415161718
def twoSumSorted(nums, target):
    left = 0
    right = len(nums) - 1
    
    while left < right:
        current_sum = nums[left] + nums[right]
        
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            # Sum is too small. We need a bigger number. Move left pointer up.
            left += 1
        else:
            # Sum is too big. We need a smaller number. Move right pointer down.
            right -= 1
            
    return []
# Time: O(N), Space: O(1)

*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.

java
12345678910111213141516
public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    
    int slow = 0; // Tracks the position of the last unique element
    
    for (int fast = 1; fast < nums.length; fast++) {
        // If we find a NEW unique element
        if (nums[fast] != nums[slow]) {
            slow++; // Move slow pointer forward
            nums[slow] = nums[fast]; // Overwrite duplicate with new unique element
        }
    }
    // Length is index + 1
    return slow + 1; 
}
// Time: O(N), Space: O(1)

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 mid across 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 left at 0, right at 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. 1. left = 0, right = length - 1.
  1. 2. While left < right:
  1. 3. Swap arr[left] and arr[right].
  1. 4. left++, right--.

8. Common Mistakes

  • Infinite Loops: Forgetting to explicitly increment/decrement the pointers inside the while loop, causing the program to freeze.
  • Incorrect while Condition: Using while left <= right when you shouldn't. If left == right, they are pointing to the exact same element. If the problem requires *two distinct* elements, the condition MUST be while 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. 1. If you use Fast (moves 2 steps) and Slow (moves 1 step) pointers on a Linked List, what happens when Fast reaches the end of the list? Where is Slow?
  1. 2. Why does the Opposite-End pointer technique (Two Sum II) fail if the array is NOT sorted?

11. MCQs

Question 1

What is the primary architectural goal of using the Two Pointer technique?

Question 2

The "Opposite-End Pointers" pattern (one at index 0, one at the last index) relies heavily on what prerequisite?

Question 3

In the Two Sum II (Sorted Array) problem, what happens when current_sum > target?

Question 4

What is the standard while loop condition for Opposite-End pointers requiring two *distinct* elements?

Question 5

How do the pointers behave in the "Fast and Slow Pointers" (Tortoise and Hare) pattern?

Question 6

When removing duplicates from a sorted array in-place, what is the role of the Slow pointer?

Question 7

In the "Container With Most Water" problem, why do you always move the pointer pointing to the *shorter* line inward?

Question 8

What is a common pitfall that causes an Infinite Loop when implementing Two Pointers?

Question 9

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?

Question 10

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?
A: Yes. "Sorted Array" is an massive interview hint. It means the answer is either Two Pointers (O(N)) or Binary Search (O(log N)).

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 your while loop conditions to prevent infinite loops, and ensure you explicitly move your pointers based on logical deductions.

17. Next Chapter Recommendation

Two pointers let us look at two specific elements. But what if we need to look at a continuous "chunk" of elements, like a subarray? In Chapter 6: Sliding Window Problems, we will learn the ultimate technique for subarray optimization.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·