15% off all plans & roadmaps Use code
See plansTwo Sum II - Input Array Is Sorted
- LeetCode 167
- Medium
- Two Pointers
- Converging (Sorted Array Target Sum)
Updated
TL;DR: Find two numbers in a sorted array that add to a target and return their 1-based indices. Put one pointer at each end and move the one that fixes the sum, which takes O(n) time and O(1) space.
Problem
You are given a 1-indexed array of integers numbers that is already sorted in non-decreasing order. Find two numbers whose sum equals a given target. Call them numbers[index1] and numbers[index2], where 1 <= index1 < index2 <= numbers.length.
Return the two indices, each increased by one, as an integer array [index1, index2] of length 2.
The tests guarantee exactly one solution. You may not use the same element twice. Your solution must use only constant extra space.
Example 1
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: 2 + 7 = 9, so index1 = 1 and index2 = 2.
Example 2
Input: numbers = [2,3,4], target = 6 Output: [1,3] Explanation: 2 + 4 = 6, so index1 = 1 and index2 = 3.
Example 3
Input: numbers = [-1,0], target = -1 Output: [1,2] Explanation: -1 + 0 = -1, so index1 = 1 and index2 = 2.
Constraints
2 <= numbers.length <= 3 * 10^4-1000 <= numbers[i] <= 1000numbersis sorted in non-decreasing order.-1000 <= target <= 1000- The tests are generated so that there is exactly one solution.
Constraints that matter
- n up to 3 * 10^4 means an O(n^2) pair check does about 4.5 * 10^8 comparisons in the worst case. That is risky, so aim for O(n) or O(n log n).
- The array is sorted, so every comparison against the target tells you which direction to move. This is what makes a pointer scan possible.
- The problem demands constant extra space. This rules out the hash map you would use in the unsorted Two Sum.
- Exactly one solution exists, so a scan that finds a pair can return at once and needs no tie-breaking or duplicate handling.
- Values stay within -1000 to 1000, so sums never overflow a 32-bit integer in any language.
- Output is 1-based. Every approach must add one to the 0-based positions.
Hints
Hint 1
This is the two pointers pattern, in its converging form.
Hint 2
Try every pair of positions i < j and check whether nums[i] + nums[j] equals the target.
Solution
Intuition
This is the two pointers pattern, in its converging form. The signal is a sorted array plus a target sum. Sorting means that moving an index right never lowers a value and moving it left never raises one.
Picture two readers scanning a sorted price list from opposite ends, hunting for two items that total a fixed budget. The high end crosses off its item when the total is too big, and the low end crosses off its item when too small.
Place one pointer on the smallest value and one on the largest. Their sum is either too big, too small, or exact. If it is too big, the right value is too large to pair with anything. Even the smallest remaining partner, the one at the left pointer, overshoots, so you can discard the right value for good.
The same reasoning works on the other side. If the sum is too small, the left value cannot pair with anything. Even the largest remaining partner falls short. Discard it and move the left pointer right.
Each step throws away one index that cannot be in the answer. The window shrinks by one each time, so after at most n - 1 steps you either find the pair or the pointers meet. Because a solution is guaranteed, you always find it first.
Worked example
Input: numbers = [2, 7, 11, 15], target = 9 Output: [1, 2] Explanation: The values 2 and 7 sit at 0-based positions 0 and 1 and add up to 9. Adding one to each position gives the 1-based answer [1, 2].
Approach 1: Brute force
Try every pair of positions i < j and check whether nums[i] + nums[j] equals the target. This is the solution you write before you notice anything special about the input. It ignores the sort order completely.
It is correct, and it uses O(1) extra space. The cost is time, since it re-adds many pairs that the sort order already rules out.
Steps
- Loop
ifrom 0 to n - 2. - For each
i, loopjfromi + 1to n - 1. - Compute
nums[i] + nums[j]. - If it equals the target, return
[i + 1, j + 1]. - Return an empty array at the end. The guarantee means this line never runs.
Dry run
On [2, 7, 11, 15] with target 9:
i = 0,j = 1: 2 + 7 = 9. This equals the target, so return[1, 2].
The first pair checked is the answer here. In the worst case the answer is the last pair, and the loops run n * (n - 1) / 2 times.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Here n is the array length. The outer loop runs about n times, and the inner loop runs n - i - 1 times, so the total is n * (n - 1) / 2 pair checks, which is O(n^2). You store only two indices and a sum, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n - 1):
# scan j from the right so duplicates pick the outermost pair
for j in range(n - 1, i, -1):
if nums[i] + nums[j] == target:
return [i + 1, j + 1]
return []JavaTested in our runner
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
// smallest i first; for each i scan j from the right so duplicates resolve to the last index
for (int i = 0; i < n - 1; i++) {
for (int j = n - 1; j > i; j--) {
if (nums[i] + nums[j] == target) {
return new int[] { i + 1, j + 1 };
}
}
}
return new int[0];
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
// scan j from the right so ties resolve to the largest j
for (int j = n - 1; j > i; j--) {
if (nums[i] + nums[j] == target) {
return {i + 1, j + 1};
}
}
}
return {};
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const n = nums.length;
// Brute force over all pairs, scanning the right index from the end
// so ties resolve to the same pair a two-pointer scan would find
for (let j = n - 1; j > 0; j--) {
for (let i = 0; i < j; i++) {
if (nums[i] + nums[j] === target) {
return [i + 1, j + 1];
}
}
}
return [];
};GoTested in our runner
func twoSum(nums []int, target int) []int {
n := len(nums)
for i := 0; i < n-1; i++ {
// scan j from the right so duplicates resolve to the last matching index
for j := n - 1; j > i; j-- {
if nums[i]+nums[j] == target {
return []int{i + 1, j + 1}
}
}
}
return []int{}
}C#Tested in our runner
public class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.Length;
// Smallest i first, and for that i the largest j (matches expected tie-breaking with duplicates)
for (int i = 0; i < n - 1; i++) {
for (int j = n - 1; j > i; j--) {
if (nums[i] + nums[j] == target) {
return new int[] { i + 1, j + 1 };
}
}
}
return new int[0];
}
}Approach 2: Binary search for the partner
What's slow: the inner loop scans every later element to find the partner of nums[i]. That is a linear search over data that is already sorted.
The insight that fixes it: for each i, the partner must equal target - nums[i], and a sorted range can be searched in O(log n). Search only the positions after i, so you never reuse the same element.
Steps
- Loop
ifrom 0 to n - 2. - Compute
need = target - nums[i]. - Set
lo = i + 1andhi = n - 1. - While
lo <= hi, computemid. Ifnums[mid] == need, return[i + 1, mid + 1]. - If
nums[mid] < need, setlo = mid + 1. Otherwise sethi = mid - 1. - Move on to the next
iwhen the range is empty.
Dry run
On [2, 7, 11, 15] with target 9:
i = 0,need = 7,lo = 1,hi = 3.mid = 2, value 11 is greater than 7, sohi = 1.mid = 1, value 7 equals 7, so return[1, 2].
Two probes replaced a scan over three elements.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(1) |
Here n is the array length. The outer loop runs at most n times, and each binary search halves a range of at most n elements, so it takes at most about log2(n) probes. That gives O(n log n) time. The search uses a few integer variables, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n - 1):
need = target - nums[i]
lo, hi = i + 1, n - 1
found = -1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == need:
# record and keep searching right for the last occurrence
found = mid
lo = mid + 1
elif nums[mid] < need:
lo = mid + 1
else:
hi = mid - 1
if found != -1:
return [i + 1, found + 1]
return []JavaTested in our runner
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n - 1; i++) {
int need = target - nums[i];
int lo = i + 1;
int hi = n - 1;
int found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == need) {
// record and keep searching right for the last occurrence
found = mid;
lo = mid + 1;
} else if (nums[mid] < need) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (found != -1) {
return new int[] { i + 1, found + 1 };
}
}
return new int[0];
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
int need = target - nums[i];
int lo = i + 1;
int hi = n - 1;
int found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == need) {
// record and keep searching right for the last occurrence
found = mid;
lo = mid + 1;
} else if (nums[mid] < need) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (found != -1) {
return {i + 1, found + 1};
}
}
return {};
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const n = nums.length;
for (let i = 0; i < n - 1; i++) {
const need = target - nums[i];
let lo = i + 1;
let hi = n - 1;
// find the rightmost position with value <= need
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (nums[mid] <= need) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (hi >= i + 1 && nums[hi] === need) {
return [i + 1, hi + 1];
}
}
return [];
};GoTested in our runner
func twoSum(nums []int, target int) []int {
n := len(nums)
for i := 0; i < n-1; i++ {
need := target - nums[i]
lo, hi := i+1, n-1
res := -1
// find the rightmost index holding need
for lo <= hi {
mid := lo + (hi-lo)/2
if nums[mid] <= need {
if nums[mid] == need {
res = mid
}
lo = mid + 1
} else {
hi = mid - 1
}
}
if res >= 0 {
return []int{i + 1, res + 1}
}
}
return []int{}
}C#Tested in our runner
public class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.Length;
for (int i = 0; i < n - 1; i++) {
int need = target - nums[i];
int lo = i + 1;
int hi = n - 1;
int found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == need) {
// record the match and keep looking right for the last duplicate
found = mid;
lo = mid + 1;
} else if (nums[mid] < need) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (found != -1) {
return new int[] { i + 1, found + 1 };
}
}
return new int[0];
}
}Approach 3: One-pass hash map
What's slow: binary search still spends log n work on every index. Each search starts from scratch and remembers nothing about the elements already seen.
The insight that fixes it: store each value's index as you pass it. At position i, the partner you need is target - nums[i]. If it is already in the map, you are done. Otherwise record nums[i] and move on.
This is the standard Two Sum answer, and it ignores the sort order. It breaks the constant-space rule, because the map can hold up to n - 1 entries. You should still know it, since an interviewer often asks you to compare it with the pointer solution.
Steps
- Create an empty map from value to 0-based index.
- Loop
ifrom 0 to n - 1. - Compute
need = target - nums[i]. - If
needis in the map, return[map[need] + 1, i + 1]. - Otherwise store
map[nums[i]] = i. - Return an empty array at the end. The guarantee means this line never runs.
Dry run
On [2, 7, 11, 15] with target 9:
i = 0, value 2, need 7. The map is empty, so store it. The map is now{2: 0}.i = 1, value 7, need 2. The map has 2 at index 0, so return[0 + 1, 1 + 1] = [1, 2].
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the array length. The loop visits each element once, and each map lookup and insert costs O(1) on average, so time is O(n). The map can hold up to n - 1 entries before the answer appears, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# map each value to its last index
last = {}
for i, x in enumerate(nums):
last[x] = i
# the smallest i with a valid partner gives the outermost pair, as two pointers would
for i, x in enumerate(nums):
j = last.get(target - x)
if j is not None and j > i:
return [i + 1, j + 1]
return []
JavaTested in our runner
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
// map value -> last index
Map<Integer, Integer> last = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
last.put(nums[i], i);
}
// take the pair with the smallest first index
for (int i = 0; i < nums.length; i++) {
Integer j = last.get(target - nums[i]);
if (j != null && j > i) {
return new int[] { i + 1, j + 1 };
}
}
return new int[0];
}
}C++Tested in our runner
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// map each value to its last index
unordered_map<int, int> last;
for (int i = 0; i < (int)nums.size(); i++) {
last[nums[i]] = i;
}
// smallest i with a partner after it gives the outermost pair
for (int i = 0; i < (int)nums.size(); i++) {
auto it = last.find(target - nums[i]);
if (it != last.end() && it->second > i) {
return {i + 1, it->second + 1};
}
}
return {};
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
// Map each value to its last index
const last = new Map();
for (let i = 0; i < nums.length; i++) {
last.set(nums[i], i);
}
// Smallest first index with a partner at a later position
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (last.has(need) && last.get(need) > i) {
return [i + 1, last.get(need) + 1];
}
}
return [];
};GoTested in our runner
func twoSum(nums []int, target int) []int {
// map each value to its last index
idx := make(map[int]int, len(nums))
for i, x := range nums {
idx[x] = i
}
// the first i with a partner after it gives the outermost pair
for i, x := range nums {
if j, ok := idx[target-x]; ok && j > i {
return []int{i + 1, j + 1}
}
}
return []int{}
}C#Tested in our runner
using System.Collections.Generic;
public class Solution {
public int[] twoSum(int[] nums, int target) {
// map each value to its last index
var last = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
last[nums[i]] = i;
}
// smallest left index first, partner must lie to the right
for (int i = 0; i < nums.Length; i++) {
if (last.TryGetValue(target - nums[i], out int j) && j > i) {
return new int[] { i + 1, j + 1 };
}
}
return new int[0];
}
}
Solution pattern
Converging (Sorted Array Target Sum)
Part of Two Pointers
Approach 4: Two pointers from both endsOptimalConverging (Sorted Array Target Sum)
What's slow: the hash map needs O(n) memory, and binary search pays a log factor. Both ignore that the sort order lets one comparison eliminate a whole index.
The insight that fixes it: start with left = 0 and right = n - 1. If nums[left] + nums[right] is above the target, nums[right] cannot pair with any remaining value, so decrement right. If it is below, nums[left] cannot pair with any remaining value, so increment left. Each step discards one index, and the loop ends in at most n - 1 steps.
The invariant is that the answer pair always lies inside [left, right]. Say the answer is at positions (i, j) and left <= i, right > j. Then nums[left] + nums[right] >= nums[i] + nums[right] > nums[i] + nums[j] = target whenever the right value is strictly larger. So the rule never skips past j. With equal values at right and j, the sum equals the target and you return at once.
Steps
- Set
left = 0andright = n - 1. - Loop while
left < right. - Compute
s = nums[left] + nums[right]. - If
s == target, return[left + 1, right + 1]. - If
s > target, decrementright. - If
s < target, incrementleft. - Return an empty array after the loop. The guarantee means this line never runs.
Dry run
On [2, 7, 11, 15] with target 9:
| Step | left | right | nums[left] + nums[right] | Compare to 9 | Action |
|---|---|---|---|---|---|
| 1 | 0 | 3 | 2 + 15 = 17 | greater | right = 2 |
| 2 | 0 | 2 | 2 + 11 = 13 | greater | right = 1 |
| 3 | 0 | 1 | 2 + 7 = 9 | equal | return [1, 2] |
The 15 and the 11 were each ruled out after one comparison. The result [1, 2] matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the array length. Every iteration moves either left right or right left, and the pointers never move back. The gap right - left starts at n - 1 and shrinks by one per step, so there are at most n - 1 iterations. You store only two indices and a sum, so extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s == target:
return [left + 1, right + 1]
if s > target:
right -= 1 # right value is too big for any partner
else:
left += 1 # left value is too small for any partner
return []
JavaTested in our runner
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int s = nums[left] + nums[right];
if (s == target) {
return new int[] { left + 1, right + 1 };
}
if (s > target) {
right--; // right value is too big for any partner
} else {
left++; // left value is too small for any partner
}
}
return new int[0];
}
}
C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int left = 0;
int right = (int)nums.size() - 1;
while (left < right) {
int s = nums[left] + nums[right];
if (s == target) {
return {left + 1, right + 1};
}
if (s > target) {
right--; // right value is too big for any partner
} else {
left++; // left value is too small for any partner
}
}
return {};
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const s = nums[left] + nums[right];
if (s === target) {
return [left + 1, right + 1];
}
if (s > target) {
right--; // right value is too big for any partner
} else {
left++; // left value is too small for any partner
}
}
return [];
};
GoTested in our runner
func twoSum(nums []int, target int) []int {
left, right := 0, len(nums)-1
for left < right {
s := nums[left] + nums[right]
if s == target {
return []int{left + 1, right + 1}
}
if s > target {
right-- // right value is too big for any partner
} else {
left++ // left value is too small for any partner
}
}
return []int{}
}
C#Tested in our runner
public class Solution {
public int[] twoSum(int[] nums, int target) {
int left = 0;
int right = nums.Length - 1;
while (left < right) {
int s = nums[left] + nums[right];
if (s == target) {
return new int[] { left + 1, right + 1 };
}
if (s > target) {
right--; // right value is too big for any partner
} else {
left++; // left value is too small for any partner
}
}
return new int[0];
}
}
Common mistakes
- Returning
[left, right]instead of[left + 1, right + 1]. The problem is 1-indexed, so every answer needs the +1 on both values. - Writing
while left <= right. When the pointers meet, the loop pairs an element with itself, and with a target of 2 * x it can return a wrong answer. Useleft < right. - Starting the binary search at index 0 or at
iinstead ofi + 1. The search can then findnums[i]itself as its own partner. Search only the range afteri. - Writing
seen[x] = ibefore theneed in seencheck in the hash map version. Withnums = [3, 4]and target 6, the element would match itself. Look up first, then insert. - Moving both pointers on a mismatch, or moving the wrong one. If the sum is too big, only
right--can lower it, and if it is too small, onlyleft++can raise it. Moving both skips valid pairs. - Reaching for the hash map and calling it done. It passes the tests but breaks the constant-space requirement the problem states. The sorted input exists so that you can avoid the map.
Edge cases
[-1, 0]with target -1: the smallest legal input has length 2 and negatives. The answer is[1, 2].[3, 3]with target 6: duplicate values at two different positions are valid. The answer is[1, 2], and it must not pair an element with itself.[2, 3, 4]with target 6: the pair is 2 and 4, so the answer is[1, 3]. A solution must not return index 2 twice for 3 + 3.[1, 2, 3, 4, 4, 9, 56, 90]with target 8: the two 4s at positions 4 and 5 are the answer,[4, 5]. Duplicates must not confuse the pointers.- The pair sits at the extreme ends, such as
[1, 5, 8, 20]with target 21: the pointers match on the first step and return[1, 4]. - Maximum size, n = 30000 with the answer near the middle: only the O(n) or O(n log n) approaches finish comfortably, and the pointer scan takes about 15000 steps.
Follow-ups interviewers ask
- What if the array were not sorted?
- Then the pointer argument fails, because one comparison no longer says which side to move. Use the one-pass hash map from the original Two Sum, which is O(n) time and O(n) space. If you must keep O(1) space, sort a copy of the indices and run the pointers, which costs O(n log n).
- What if you needed every pair that hits the target, with no repeated value pairs?
- Keep the converging pointers, but do not return on a match. Record the pair, move both pointers inward, and then skip over any equal values on each side. This avoids duplicate pairs. It still runs in O(n) time after the array is sorted.
- How would you extend this to three numbers?
- Fix one index with an outer loop and run the converging pointers on the part of the array to its right for the remaining target. That is O(n^2) total, which beats the O(n^3) triple loop. It is the basis of the 3Sum solution, and 4Sum adds another loop around it.
Two Sum II - Input Array Is Sorted FAQ
How can I solve LeetCode 167, Two Sum II - Input Array Is Sorted?
Use two pointers. Put left at the first index and right at the last. If their sum is above the target, move right left. If it is below, move left right. When the sum matches, return both indices plus one.
What is the time complexity of Two Sum II?
The two-pointer solution is O(n) time, where n is the array length. Each step moves one pointer toward the other and neither moves back, so there are at most n - 1 steps. Extra space is O(1). The brute force is O(n^2) and the binary search version is O(n log n).
Why use two pointers for Two Sum II?
The array is sorted, so the sum of the two end values tells you which end to drop. A sum that is too large means the right value is too large for every remaining partner. A sum that is too small means the left value is too small. This lets you eliminate one index per step with no extra memory.
Can Two Sum II be solved in O(1) extra space?
Yes. The two-pointer scan uses two indices and one sum, so extra space is constant, and time is O(n). The hash map solution needs O(n) space, which is why the problem forbids it. Binary search also uses O(1) space but takes O(n log n) time.
Do I need to sort the array first?
No. The input is already sorted in non-decreasing order, so sorting would waste O(n log n) time. It would also change the index positions you must return. Sorting is only needed in the unsorted Two Sum variant when you want constant extra space.
Is Two Sum II harder than Two Sum?
The code is shorter, but the reasoning is different. You must justify why moving a pointer never skips the answer, and the problem rules out the hash map. LeetCode labels it Medium for that reason.
Asked at
See which companies ask this — Pro
Related problems
- 3Sum · same technique: Converging (Sorted Array Target Sum)
- Container With Most Water · same technique: Converging (Sorted Array Target Sum)
- 4Sum · same technique: Converging (Sorted Array Target Sum)
- Boats to Save People · same technique: Converging (Sorted Array Target Sum)
- 3Sum Closest · same technique: Converging (Sorted Array Target Sum)
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers