Two Sum II (Input Array Is Sorted) (LeetCode 167): Solution and Explanation
Given a sorted array of integers and a target, find the two distinct positions whose values add up to the target and return them as 1-indexed positions. Exactly one answer exists, and the solution should use constant extra space.
Watch it run step by step
Try your own input and write the code →Intuition
The original Two Sum is solved with a hash map, and that still works here, but it uses O(n) memory and ignores the one fact this version gives you: the array is sorted. Sorted order means that moving right always gives you a value at least as large, and moving left a value at least as small. That monotonic structure lets you steer toward the target instead of searching blindly.
Start with the smallest and largest elements, l at the front and r at the back. If their sum is too big, the only way to shrink it is to use a smaller number, and since numbers[l] is already the smallest available partner for numbers[r], the element at r cannot be part of any pair that works. So discard it by moving r left. If the sum is too small, the same argument says numbers[l] cannot be in the answer, because even its largest possible partner is too small, so move l right.
Each step eliminates one element for good, and the true pair is never eliminated, because you only throw away an element after proving it has no valid partner left. The pointers therefore converge on the answer in at most n - 1 steps, using just two integers of memory.
A useful way to picture it is a grid whose rows are the left index and columns the right index, with each cell holding the pair's sum. Because the array is sorted, sums increase to the right and downward. Starting at the top right corner, a sum that is too large rules out a whole column and a sum that is too small rules out a whole row, so you walk a staircase path to the answer instead of visiting the whole grid.
Approach: Two pointers from both ends
- Set
l = 0andr = len(numbers) - 1. - While
l < r, computecurSum = numbers[l] + numbers[r]. - If
curSum > target, decrementrto try a smaller value. - If
curSum < target, incrementlto try a larger value. - Otherwise the sum matches, so return
[l + 1, r + 1]to convert to 1-indexed positions. - Return an empty list if the loop ends, which cannot happen when an answer is guaranteed.
Step-by-step example
numbers = [2, 7, 11, 15], target = 9
- l = 0, r = 3: 2 + 15 = 17, which is greater than 9, so r = 2.
- l = 0, r = 2: 2 + 11 = 13, still greater than 9, so r = 1.
- l = 0, r = 1: 2 + 7 = 9, which matches. Return [1, 2].
Code: Python, Java, C++
1class Solution:
2 def twoSum(self, numbers: List[int], target: int) -> List[int]:
3 l, r = 0, len(numbers) - 1
4
5 while l < r:
6 curSum = numbers[l] + numbers[r]
7
8 if curSum > target:
9 r -= 1
10 elif curSum < target:
11 l += 1
12 else:
13 return [l + 1, r + 1]
14
15 return []1class Solution {
2 public int[] twoSum(int[] numbers, int target) {
3 int l = 0;
4 int r = numbers.length - 1;
5
6 while (l < r) {
7 int sum = numbers[l] + numbers[r];
8
9 if (sum > target) {
10 r--;
11 } else if (sum < target) {
12 l++;
13 } else {
14 return new int[] { l + 1, r + 1 };
15 }
16 }
17 return new int[0];
18 }
19}1class Solution {
2public:
3 vector<int> twoSum(vector<int>& numbers, int target) {
4 int l = 0;
5 int r = numbers.size() - 1;
6
7 while (l < r) {
8 int sum = numbers[l] + numbers[r];
9
10 if (sum > target) {
11 r--;
12 } else if (sum < target) {
13 l++;
14 } else {
15 return {l + 1, r + 1};
16 }
17 }
18 return {};
19 }
20};Time and space complexity
O(n)
Each iteration moves one pointer one step closer to the other, so there are at most n - 1 iterations of constant work.
O(1)
Only the two indices and the running sum are stored, which satisfies the constant space requirement.
Other approaches
Binary search for each complement (time O(n log n), space O(1))
For each index i, binary search the rest of the array for target - numbers[i]. It also uses constant space and exploits sorting, but it is slower than the two pointer sweep.
Hash map as in Two Sum (time O(n), space O(n))
Store each value's index and look up the complement. It does not need sorted input, but it uses O(n) memory and so misses the constant space requirement.
Common mistakes
- Returning 0-indexed positions. This problem expects 1-indexed output, so add one to each index.
- Using
l <= ras the loop condition. When the pointers meet they refer to the same element, which cannot be used twice. - Moving both pointers at once after a mismatch. Only the pointer whose element was proven useless should move, or you can skip over the answer.
- Worrying about integer overflow without checking the constraints. Values are bounded at 1,000 in magnitude, so the sum fits easily in 32 bits here, though in general a sum of two large ints can overflow in Java or C++.
Frequently asked questions
Why does the two pointer approach work for Two Sum II?
Because the array is sorted, a sum that is too large proves the right element cannot pair with anything left, and a sum that is too small proves the left element cannot pair with anything right. Discarding those elements never discards the answer.
Why does Two Sum II return 1-indexed positions?
That is simply how the problem defines its output. The algorithm works on 0-indexed arrays and adds one to each index before returning.
Can I use a hash map like the original Two Sum?
It produces the right answer, but it uses linear extra memory. The problem asks for constant space, which the two pointer method achieves.
What is the time complexity of Two Sum II?
O(n) with two pointers, since each step moves one pointer inward. Binary searching for each complement is O(n log n).