AlgorithmsTwo Pointers

Two Pointers

Maintain a pair of pointers to carry out logic efficiently, often used in sorted arrays or linked lists.

Definition

The Two Pointers technique is a pattern that uses two pointers to solve problems efficiently. These pointers typically move through an array or linked list in a specific way to find a solution. The main idea is to have a left pointer and a right pointer, both starting at different indices of the array. As we process the data, we move these pointers inward or outward based on conditions specific to the problem.

Types of Two Pointers

Opposite-direction pointers use a left pointer at the beginning and a right pointer at the end of an array. These pointers move toward each other based on comparing their values. For example, if we’re finding a target sum, we move right if the sum is too large, and left if it’s too small.


Another pattern is sliding window, where both pointers move in the same direction while maintaining a specific window size. While this technique is useful for finding subarrays with certain properties, this page focuses on opposite-direction pointers.

How it Works

The algorithm works by comparing values at two different positions and moving based on what we find. We start with a left pointer at the beginning (0) and a right pointer at the end (length - 1). During each step, we compare these values and move one of the pointers inward based on what we’re looking for.


The pointers continue moving until they meet in the middle or until we find our solution. This technique is space-efficient because it only requires two variables, and it’s time-efficient since we process each element at most once. We also avoid using any extra data structures, making this approach ideal for problems that require comparing elements from different positions.

Two Pointers: Step-by-Step

1. Initialize Two Pointers

Start with two pointers, often at opposite ends of the data structure. For example, one at the beginning and one at the end of an array. Common setups include: One pointer at the start (index 0) and one at the end (index length - 1) of an array, or pointers at specific positions based on problem constraints.

2. Move the Pointers

Based on certain conditions, move one or both pointers towards each other or in the same direction. Common patterns include: Moving pointers towards each other, or moving one pointer based on the value at the other pointer’s position.

3. Compare and Process

At each step, compare the elements at the two pointers and process them according to the problem requirements. This involves comparing values at both pointers and processing elements or updating the result.

4. Terminate

The algorithm typically terminates when the pointers meet, cross each other, or when a solution is found. Termination conditions vary: Pointers meet or cross each other, a specific condition is met, or traversing the entire data structure.
Common Patterns

Opposite-direction pointers typically use a while loop that runs until pointers meet. This pattern works best when you need to compare elements from opposite ends of sorted data. In sorted arrays, moving pointers has predictable effects - moving right always gives us a smaller value, while moving left gives us a larger one. This predictability helps us efficiently navigate toward our target.

Two Pointers

class Solution:
    def twoPointers(self, numbers: List[int], target: int) -> List[int]:
        # Step 1: Initialize two pointers
        left, right = 0, len(numbers) - 1
        
        # Step 2: Move the pointers
        while left < right:
            # Step 3: Compare and process
            total = numbers[left] + numbers[right]
            if total < target:
                left += 1 
            elif total > target:
                right -= 1 
            # Step 4: Terminate (target found)
            else:
                return [left + 1, right + 1]  
        
        # Step 4: Terminate (when loop ends)
        return []

Palindrome problems are another natural fit for Two Pointers because they require comparing characters from both ends of a string. By checking if characters match while moving inward, we can quickly validate palindromes without needing to store or compare the entire string at once.

Best Practices

Understanding the Two Pointers technique is important for solving many coding interview problems efficiently. These best practices will help you implement this technique effectively and avoid common pitfalls:


Two Pointers are useful for problems involving sorted arrays, strings, or linked lists where you need to find pairs with certain characteristics. It’s effective when you need to compare elements from different positions in the data structure.

Practice Problems
Two Pointers
Completed
Title
Notes
Solution
Easy
Medium
Medium
Medium
Medium
Medium
Hard

Copyright © StudyDSA. All rights reserved.