The “Two Sum II – Input Array Is Sorted” problem asks you to find two numbers in a sorted array that add up to a specific target and return their 1-based indices. The key insight is that the array is already sorted, which enables a much more efficient solution than brute-force searching.
Example:
numbers = [2, 7, 11, 15]
, target = 9
[1, 2]
(because 2 + 7 = 9
)This problem is a classic use case for the two-pointer technique, optimized for sorted arrays. It emphasizes the importance of leveraging input constraints (sortedness) to improve performance, a key strategy in competitive programming and software engineering.
A brute-force method would check every pair of elements to find a match — which works but is inefficient at O(n²)
time complexity. Thankfully, since the input array is sorted, we can solve it in linear time using a two-pointer approach.
The two-pointer technique involves scanning the array from both ends toward the center. At each step, you check the sum of the elements pointed to by the left and right pointers.
left = 0
(start of array)right = numbers.length - 1
(end of array)left < right
:
sum = numbers[left] + numbers[right]
sum == target
, return [left + 1, right + 1]
(1-based indexing)sum < target
, increment left
to increase the sumsum > target
, decrement right
to decrease the sum
Input: numbers = [2, 3, 4]
, target = 6
2 + 4 = 6
[1, 3]
Time Complexity: O(n), where n is the number of elements. Each element is visited at most once.
Space Complexity: O(1), since the solution uses only two pointers and no extra data structures.
The “Two Sum II” problem is an elegant demonstration of the power of two-pointer strategies. By leveraging the sorted nature of the input, we eliminate the need for nested loops and achieve linear performance with constant space usage. It's a textbook case for writing clean, efficient, and optimal code using minimal memory.