✌️ Two Pointer Algorithm in Python – Explained with Example

🔍 What is the Two Pointer Technique?

The two-pointer technique is a common algorithmic approach used to reduce time complexity in problems involving arrays or strings. It uses two pointers (usually left and right) to iterate through the structure smartly, often avoiding the need for nested loops.


📌 When to Use Two Pointers

  • You need to find a pair or triplet with certain properties in an array.
  • You're asked to sort, search, or compare elements in a sorted array.
  • Problems involve reversing, removing duplicates, or merging arrays.
  • Efficient solutions to problems like Longest Substring, Palindrome Check, etc.


⚙️ Basic Idea

left = 0
right = len(array) - 1

while left < right:
    # Do something with array[left] and array[right]
    
    if some_condition:
        left += 1
    else:
        right -= 1
        

✅ Example Problem – "Two Sum II – Input Array is Sorted"

🔸 LeetCode #167 🔸 Problem Statement: Given a sorted array of integer numbers, and an integer target, return the indices (1-indexed) of the two numbers such that they add up to the target.

You must use only constant extra space, and the solution must be in O(n) time.


🧠 Intuition

Since the array is sorted, we can take advantage of that:

  • Place one pointer at the beginning (left) and one at the end (right).
  • If the sum of the two elements is less than the target, move the left pointer to the right (to increase the sum).
  • If the sum is more than the target, move the right pointer to the left (to decrease the sum).
  • If equal, return the indices.


🧪 Python Solution (Two Pointer)

def two_sum_sorted(numbers, target):
    left = 0
    right = len(numbers) - 1

    while left < right:
        current_sum = numbers[left] + numbers[right]

        if current_sum == target:
            return [left + 1, right + 1]  # 1-indexed
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    
    return []  # If no solution found
        

🧾 Example

numbers = [2, 7, 11, 15]
target = 9

print(two_sum_sorted(numbers, target))
        

💥 Output:

[1, 2]
        

Because numbers[0] + numbers[1] = 2 + 7 = 9, which matches the target.


📊 Time and Space Complexity

Metric Complexity Time Complexity O(n) Space Complexity O(1)


🔁 Other Examples You Can Try

  1. Reverse a string using two pointers.
  2. Check if a string is a palindrome.
  3. Container With Most Water (LeetCode #11).
  4. Move Zeroes (two pointers for in-place array manipulation).


To view or add a comment, sign in

More articles by Mostafa Shariare

Explore content categories