Algo-Sim › Two Pointers
Two Sum II - Input Array Is Sorted
Medium · Two Pointers · step through it in Java, Python and C++ on your own input
In a sorted array, find the two numbers that add up to the target, using O(1) extra space.
Problem
You are given a 1-indexed array numbers sorted in non-decreasing order and a target. Exactly one pair of different positions holds values that add up to target; return those two positions as [index1, index2] with index1 < index2. Use only constant extra space.
Constraints
- 2 ≤ numbers.length ≤ 3 · 10⁴
- -1000 ≤ numbers[i], target ≤ 1000
- numbers is sorted in non-decreasing order
- Exactly one solution exists; O(1) extra space
Edge cases to test
- The pair uses the first and last element
- Duplicate values:
[2, 2, 3], target 4 - Negative numbers
Follow-up questions
- Why is moving the smaller pointer safe?
- If the sum is too small, the left value can’t pair with anything to the left of right, so it can be dropped: each step discards one candidate for good.
- Why not binary search for each complement?
- That is O(n log n). Two pointers use the sorted order on both ends at once: O(n), O(1) space.
Solution
Java
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[] { left + 1, right + 1 };
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[] { -1, -1 };
}Python
def two_sum(numbers, target):
left, right = 0, len(numbers) - 1
while left < right:
total = numbers[left] + numbers[right]
if total == target:
return [left + 1, right + 1]
elif total < target:
left += 1
else:
right -= 1
return [-1, -1]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int left = 0, right = int(numbers.size()) - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return vector<int>{left + 1, right + 1};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return vector<int>{-1, -1};
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)