✌️ 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
⚙️ 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:
🧪 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