AlgorithmsTwo Pointers

Two Pointers

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

Definition of Two Pointers

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.

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.
Implementation of Two Pointers

Let's look at a classic example of the Two Pointers technique: the "Two Sum II" problem. In this problem, we're given a sorted array of integers and a target sum. We need to find two numbers in the array that add up to the target sum.

class Solution:
    def twoSum(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 (solution found)
            else:
                return [left + 1, right + 1]  
        
        # Step 4: Terminate (when loop ends)
        return []

In this example, we start with two pointers: left at the beginning of the array and right at the end. We move these pointers based on whether the current sum is less than, equal to, or greater than the target sum. This approach works because the array is sorted, allowing us to efficiently narrow down the search space.

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 Two Pointers
Two Pointers
Completed
Title
Notes
Solution
Easy
Medium
Medium
Medium
Medium
Medium
Hard

Copyright © StudyDSA. All rights reserved.