Two Sum II - Input Array Is Sorted
Two Sum II - Input Array Is Sorted is a medium arrays & hashing problem solved with the two pointer pattern.
The best approach, optimal (two pointers), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (binary search for the partner) up.
Problem
The array numbers is sorted in non-decreasing order. Find two numbers that add up to target and return their positions as a 1-indexed pair [index1, index2] with index1 < index2.
Use only constant extra space.
Examples
Example 1
- Input
numbers = [1, 3, 4, 6, 9], target = 10- Output
[2, 5]- Why
- numbers[1] + numbers[4] = 1 + 9 = 10, reported 1-indexed.
Example 2
- Input
numbers = [-3, -1, 0], target = -1- Output
[2, 3]
Constraints
2 <= numbers.length <= 3 * 10^4- numbers is sorted in non-decreasing order.
- Exactly one solution exists. Use only constant extra space.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (binary search for the partner) | O(n log n) | O(1) |
| Optimal (two pointers) | O(n) | O(1) |
1Brute force (binary search for the partner)
O(n log n)O(1)For each index i, binary search the rest of the array for target - numbers[i].
- For each i, search numbers[i + 1..n - 1] for target - numbers[i].
- Return the 1-indexed pair when found.
class Solution {
public int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
int need = target - numbers[i];
int lo = i + 1, hi = numbers.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (numbers[mid] == need) return new int[] { i + 1, mid + 1 };
if (numbers[mid] < need) lo = mid + 1; else hi = mid - 1;
}
}
return new int[0];
}
}class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
for i in range(len(numbers)):
need = target - numbers[i]
lo, hi = i + 1, len(numbers) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if numbers[mid] == need:
return [i + 1, mid + 1]
if numbers[mid] < need:
lo = mid + 1
else:
hi = mid - 1
return []class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
for (int i = 0; i < (int) numbers.size(); i++) {
int need = target - numbers[i];
int lo = i + 1, hi = numbers.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (numbers[mid] == need) return {i + 1, mid + 1};
if (numbers[mid] < need) lo = mid + 1; else hi = mid - 1;
}
}
return {};
}
};function twoSum(numbers, target) {
for (let i = 0; i < numbers.length; i++) {
const need = target - numbers[i];
let lo = i + 1, hi = numbers.length - 1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (numbers[mid] === need) return [i + 1, mid + 1];
if (numbers[mid] < need) lo = mid + 1; else hi = mid - 1;
}
}
return [];
}2Optimal (two pointers)
O(n)Each step moves one pointer inward, at most n steps.O(1)Start with the smallest and largest values. If their sum is too small, the left value is too small for any partner, so move left forward. If too big, move right back.
- lo = 0, hi = n - 1.
- sum < target: lo++. sum > target: hi--.
- On a match return [lo + 1, hi + 1].
class Solution {
public int[] twoSum(int[] numbers, int target) {
int lo = 0, hi = numbers.length - 1;
while (lo < hi) {
int sum = numbers[lo] + numbers[hi];
if (sum == target) return new int[] { lo + 1, hi + 1 };
if (sum < target) lo++; else hi--;
}
return new int[0];
}
}class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
lo, hi = 0, len(numbers) - 1
while lo < hi:
total = numbers[lo] + numbers[hi]
if total == target:
return [lo + 1, hi + 1]
if total < target:
lo += 1
else:
hi -= 1
return []class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int lo = 0, hi = numbers.size() - 1;
while (lo < hi) {
int sum = numbers[lo] + numbers[hi];
if (sum == target) return {lo + 1, hi + 1};
if (sum < target) lo++; else hi--;
}
return {};
}
};function twoSum(numbers, target) {
let lo = 0, hi = numbers.length - 1;
while (lo < hi) {
const sum = numbers[lo] + numbers[hi];
if (sum === target) return [lo + 1, hi + 1];
if (sum < target) lo++; else hi--;
}
return [];
}Edge cases to test
- Negative numbers
- Duplicates such as [2, 2] with target 4
Hints
Hint 1
If the sum of the two ends is too big, which end can never be part of the answer?
FAQ
What is the best time complexity for Two Sum II - Input Array Is Sorted?
Optimal (two pointers) runs in O(n) time and O(1) extra space. Each step moves one pointer inward, at most n steps.
Which pattern does Two Sum II - Input Array Is Sorted use?
It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Valid Triangle Number, Container With Most Water, Trapping Rain Water.
Is there a brute force solution for Two Sum II - Input Array Is Sorted?
Yes. Brute force (binary search for the partner) takes O(n log n) time and O(1) space. For each index i, binary search the rest of the array for target - numbers[i].
Which edge cases should I test for Two Sum II - Input Array Is Sorted?
Negative numbers; Duplicates such as [2, 2] with target 4.