When working with sorted arrays, the two-pointer technique is a powerful pattern that allows you to efficiently process elements from multiple arrays simultaneously. This technique is especially useful when you need to combine or compare data that's already organized.
The core idea is simple: instead of using nested loops (which would be O(n²)), you maintain separate pointers (indices) for each array and move them independently based on your comparison logic. This allows you to process both arrays in a single pass, achieving O(n + m) time complexity.
Here's how the two-pointer pattern works in practice. Imagine you're comparing grades from two different classes to find all students who scored above 85:
def find_high_scorers(class1_grades, class2_grades): high_scorers = [] i, j = 0, 0 # Pointers for each array while i < len(class1_grades) and j < len(class2_grades): if class1_grades[i] >= 85: high_scorers.append(f"Class1 student {i}: {class1_grades[i]}") if class2_grades[j] >= 85: high_scorers.append(f"Class2 student {j}: {class2_grades[j]}") # Move both pointers forward i += 1 j += 1 return high_scorers
The key insight is that pointers move independently - you can advance one, both, or neither based on your specific logic. When one array is exhausted (pointer reaches the end), you handle any remaining elements from the other array.
This pattern appears everywhere in programming: merging datasets, finding intersections, detecting differences between versions, and many algorithm challenges. The beauty lies in its efficiency - you never need to revisit elements you've already processed.
1def find_high_scorers(class1_grades, class2_grades):
2 high_scorers = []
3 i, j = 0, 0 # Pointers for each array
4
5 while i < len(class1_grades) and j < len(class2_grades):
6 if class1_grades[i] >= 85:
7 high_scorers.append(f"Class1 student {i}: {class1_grades[i]}")
8 if class2_grades[j] >= 85:
9 high_scorers.append(f"Class2 student {j}: {class2_grades[j]}")
10
11 # Move both pointers forward
12 i += 1
13 j += 1
14
15 return high_scorers