Two Sum II - Input Array Is Sorted
Medium
Topics
Given a 1-indexed array numbers sorted in non-decreasing order, find two numbers adding up to target. Return [index1, index2] (1-indexed) with index1 < index2.
Exactly one solution exists; use only constant extra space.
Example 1
Found at indices
[1, 2] (the answer is 1-based here).Cells are the array values; the small numbers underneath are indices.
Input: numbers = [2,7,11,15], target = 9 Output: [1,2]
Example 2
Input: numbers = [2,3,4], target = 6 Output: [1,3]
Constraints
- 2 <= numbers.length <= 3*10^4
- numbers is sorted non-decreasing.
- Exactly one solution.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Because the array is sorted, the sum of the two ends tells us which direction to move. If the pair is too small, only a larger left value helps; if too big, only a smaller right value helps.
A two-pointer sweep exploits this to reach the answer in one pass and O(1) space, beating both brute force and the hash-map approach.
Approach
- Put
lat the first index andrat the last. - Compute
s = numbers[l] + numbers[r]. - If
s == target, return the 1-based indices[l+1, r+1]. - If
s < target, incrementl(need a bigger number). Ifs > target, decrementr.
Walkthrough
numbers = [2, 7, 11, 15], target = 9
l=0 r=3 2+15=17 > 9 -> r=2
l=0 r=2 2+11=13 > 9 -> r=1
l=0 r=1 2+7 =9 == 9 -> return [1, 2]Complexity
- Time — O(n): each iteration moves one pointer inward, so together they cross the array at most once.
- Space — O(1): only two index variables.
Common Pitfalls
- This works only because the array is sorted — do not use it on unsorted input.
- The problem is 1-indexed, so add 1 to each pointer.
Full Solution — all languages
class Solution:
def twoSum(self, numbers, target):
lo, hi = 0, len(numbers) - 1
while lo < hi:
s = numbers[lo] + numbers[hi]
if s == target:
return [lo + 1, hi + 1]
if s < target:
lo += 1
else:
hi -= 1
return []import java.util.*;
class Solution {
public int[] twoSum(int[] numbers, int target) {
int lo = 0, hi = numbers.length - 1;
while (lo < hi) {
int s = numbers[lo] + numbers[hi];
if (s == target) return new int[]{lo + 1, hi + 1};
if (s < target) lo++;
else hi--;
}
return new int[]{};
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> twoSum(vector<int>& numbers, int target) {
int lo = 0, hi = (int)numbers.size() - 1;
while (lo < hi) {
int s = numbers[lo] + numbers[hi];
if (s == target) return {
lo + 1, hi + 1
};
if (s < target) lo++;
else hi--;
}
return {
};
}
};/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/ var twoSum = function(numbers, target) {
let lo = 0, hi = numbers.length - 1;
while (lo < hi) {
const s = numbers[lo] + numbers[hi];
if (s === target) return [lo + 1, hi + 1];
if (s < target) lo++;
else hi--;
}
return [];
};