Two Pointer

Not Started

The two pointer technique uses two pointers to traverse a data structure (usually an array or linked list) from different directions or at different speeds. This approach is highly efficient for problems involving sorted arrays, palindromes, and finding pairs that satisfy certain conditions.

Time Complexity: O(n) single pass with two pointers
Space Complexity: O(1) constant extra space
Use Cases: Sorted array pairs, palindromes, removing duplicates, container with most water
Pattern: Start from opposite ends and move towards center based on conditions

Implementation Examples

# Python - Two Sum in sorted array
def two_sum(arr, target):
    """Find two numbers that sum to target"""
    left, right = 0, len(arr) - 1
    
    while left < right:
        current_sum = arr[left] + arr[right]
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    
    return []

# Example: arr = [2,7,11,15], target = 9
# Output: [0, 1]
// C++ - Two Sum in sorted array
std::vector<int> twoSum(std::vector<int>& arr, int target) {
    int left = 0, right = arr.size() - 1;
    
    while (left < right) {
        int sum = arr[left] + arr[right];
        if (sum == target) {
            return {left, right};
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    
    return {};
}
// C# - Two Sum in sorted array
int[] TwoSum(int[] arr, int target) {
    int left = 0, right = arr.Length - 1;
    
    while (left < right) {
        int sum = arr[left] + arr[right];
        if (sum == target) {
            return new int[] { left, right };
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    
    return new int[] { };
}
// Java - Two Sum in sorted array
int[] twoSum(int[] arr, int target) {
    int left = 0, right = arr.length - 1;
    
    while (left < right) {
        int sum = arr[left] + arr[right];
        if (sum == target) {
            return new int[] { left, right };
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    
    return new int[] { };
}

Common Patterns

Opposite Ends: Start from both ends, move towards center
Same Direction: Both pointers move forward at different speeds (slow/fast)
Palindrome Check: Compare characters from both ends
Merge Sorted: Combine two sorted arrays efficiently