Proving that a two-pointer approach works pair sum
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
The two-pointer approach is a powerful algorithmic technique often used in problems involving arrays, such as finding pair sums, searching for target pairs, or dealing with sorted sequences. It enhances efficiency compared to traditional methods, often reducing the time complexity from O(n²) to O(n) for specific scenarios. This article will focus on proving that the two-pointer approach works for solving the pair sum problem, providing technical explanations, examples, and additional insights.
Technical Explanation
Pair Sum Problem Description
Given a sorted array of integers and a target sum, the goal is to determine whether there are two distinct numbers in the array that add up to the target sum.
Two-Pointer Technique
In the two-pointer technique, two indices are used to traverse data structures. For this problem:
- Initialization: Set one pointer (`left`) at the beginning of the array and the other pointer (`right`) at the end.
- Iterative Process:
- Calculate the sum of elements pointed to by the two pointers: `current_sum = array[left] + array[right]`.
- If `current_sum` is equal to the target sum, a valid pair is found.
- If `current_sum` is less than the target, increment the `left` pointer to increase the sum.
- If `current_sum` is greater than the target, decrement the `right` pointer to decrease the sum.
- Termination: Continue until `left` is greater than or equal to `right`.
Proof of Correctness
The correctness of the two-pointer approach can be demonstrated by considering the properties of the sorted array and the logical control of pointers:
- Sorted Array Utilization: By leveraging the sorted property, we can systematically eliminate impossible pairs by adjusting pointers, thus efficiently narrowing down possibilities.
- Pointer Adjustment: If the sum is too small, only increasing the `left` pointer can potentially lead to an increase in sum due to the sorted nature. Similarly, if the sum is too big, decreasing the `right` pointer is a logical step as it reduces the sum.
- Comprehensiveness: Each unique pair of numbers in the array is considered either directly or implicitly through the logical pointer movement.
Time Complexity Analysis
The two-pointer approach runs in O(n) time complexity as each element in the array is visited at most twice (once by each pointer). This is significantly more efficient compared to the O(n²) brute-force method, where each pair of elements is considered.
Example
Consider the sorted array `[1, 2, 3, 4, 5]` and a target sum of `6`.
| Step | Left Pointer | Right Pointer | Current Sum | Action |
| Initial | 1 (index 0) | 5 (index 4) | 6 | Pair found |
Here, `array[0] + array[4] = 1 + 5 = 6`, which equals the target. Thus, the pair `(1, 5)` is a solution.
Edge Cases
- Empty Array: The method immediately terminates as there are no elements to consider.
- Single Element Array: Impossible to find a pair, thus terminate processing.
- No Valid Pairs: The pointers will simply cross without ever yielding a sum. For example, in the array `[1, 1, 1, 1, 1]` with a target of 10.
Summary Table
| Scenario | Time Complexity | Space Complexity | Notes |
| General Functioning | O(n) | O(1) | Efficient for sorted arrays |
| Unsuitable for unsorted | - | - | Requires sorting (O(n log n) upfront) |
| Edge Case Handling | O(1) | O(1) | Efficiently handles edge cases |
Conclusion
The two-pointer approach is a practical and efficient technique for solving the pair sum problem in sorted arrays. By leveraging the properties of sorted sequences and a strategic pointer movement mechanism, this method significantly reduces computational complexity compared to naive solutions. Understanding and applying these efficient techniques is crucial for handling large datasets and improving algorithmic performance in competitive programming or software development tasks.
Related reading
- Pseudocode to compare two trees
- Push_swap sorting 50000 numbers with two rotatable stacks and a limited set of operations
- Puzzle Find largest rectangle maximal rectangle problem
- Puzzle Need an example of a complicated equivalence relation / partitioning that disallows sorting and/or hashing
- Publish multiple messages to RabbitMQ from a file
- push_back vs emplace_back
- psycopg2 insert multiple rows with one query
- Putting a LazyVStack or LazyHStack in a ScrollView causes stuttering

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.