Practice · 02 Sorted Arrays: Two Pointers · 2/5
Two Sum II - Input Array Is Sorted
Two Sum again, but sorted: no hash map needed.
Understand the problem
Back to the flight voucher from Two Sum, with one change: the add-on prices now come sorted, cheapest first. You still want two add-ons that cost exactly the voucher amount. Does the sorting help? A lot.
Given a 1-indexed array of integers
numberssorted in non-decreasing order, find two numbers that add up totarget. Return their indices as[index1, index2], with1 <= index1 < index2. There is exactly one solution, you may not use the same element twice, and your solution must use only constant extra space.
numbers | target | Output |
|---|---|---|
[2, 7, 11, 15] | 9 | [1, 2] |
[2, 3, 4] | 6 | [1, 3] |
[-1, 0] | -1 | [1, 2] |
The limits on LeetCode: 2 to 30,000 numbers, each between -1000 and 1000.
Brute force first
Try every pair, as in Two Sum.
vector<int> twoSumSortedBrute(const vector<int>& numbers, int target) {
int n = numbers.size();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) // every pair once
if (numbers[i] + numbers[j] == target) return {i + 1, j + 1}; // 1-indexed
return {};
}static int[] twoSumSortedBrute(int[] numbers, int target) {
int n = numbers.length;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) // every pair once
if (numbers[i] + numbers[j] == target) return new int[] {i + 1, j + 1}; // 1-indexed
return new int[0];
}def two_sum_sorted_brute(numbers, target):
n = len(numbers)
for i in range(n):
for j in range(i + 1, n): # every pair once
if numbers[i] + numbers[j] == target:
return [i + 1, j + 1] # 1-indexed
return []function twoSumSortedBrute(numbers, target) {
const n = numbers.length;
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++) // every pair once
if (numbers[i] + numbers[j] === target) return [i + 1, j + 1]; // 1-indexed
return [];
}func twoSumSortedBrute(numbers []int, target int) []int {
n := len(numbers)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ { // every pair once
if numbers[i]+numbers[j] == target {
return []int{i + 1, j + 1} // 1-indexed
}
}
}
return nil
}static int[] TwoSumSortedBrute(int[] numbers, int target)
{
int n = numbers.Length;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) // every pair once
if (numbers[i] + numbers[j] == target) return new[] { i + 1, j + 1 }; // 1-indexed
return Array.Empty<int>();
}O(n²): about 450 million pairs for 30,000 numbers. And it ignores the one thing the problem gave you: the order.
A better middle step: binary search for the partner
Since the array is sorted, for each numbers[i] you can binary-search the part to its right for target - numbers[i].
vector<int> twoSumSortedBinary(const vector<int>& numbers, int target) {
int n = numbers.size();
for (int i = 0; i < n; i++) {
int need = target - numbers[i];
int lo = i + 1, hi = n - 1; // search only to the right of i
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 {};
}static int[] twoSumSortedBinary(int[] numbers, int target) {
int n = numbers.length;
for (int i = 0; i < n; i++) {
int need = target - numbers[i];
int lo = i + 1, hi = n - 1; // search only to the right of i
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];
}def two_sum_sorted_binary(numbers, target):
n = len(numbers)
for i in range(n):
need = target - numbers[i]
lo, hi = i + 1, n - 1 # search only to the right of i
while lo <= hi:
mid = (lo + hi) // 2
if numbers[mid] == need:
return [i + 1, mid + 1]
if numbers[mid] < need:
lo = mid + 1
else:
hi = mid - 1
return []function twoSumSortedBinary(numbers, target) {
const n = numbers.length;
for (let i = 0; i < n; i++) {
const need = target - numbers[i];
let lo = i + 1, hi = n - 1; // search only to the right of i
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (numbers[mid] === need) return [i + 1, mid + 1];
if (numbers[mid] < need) lo = mid + 1;
else hi = mid - 1;
}
}
return [];
}func twoSumSortedBinary(numbers []int, target int) []int {
n := len(numbers)
for i := 0; i < n; i++ {
need := target - numbers[i]
lo, hi := i+1, n-1 // search only to the right of i
for lo <= hi {
mid := lo + (hi-lo)/2
if numbers[mid] == need {
return []int{i + 1, mid + 1}
}
if numbers[mid] < need {
lo = mid + 1
} else {
hi = mid - 1
}
}
}
return nil
}static int[] TwoSumSortedBinary(int[] numbers, int target)
{
int n = numbers.Length;
for (int i = 0; i < n; i++)
{
int need = target - numbers[i];
int lo = i + 1, hi = n - 1; // search only to the right of i
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (numbers[mid] == need) return new[] { i + 1, mid + 1 };
if (numbers[mid] < need) lo = mid + 1;
else hi = mid - 1;
}
}
return Array.Empty<int>();
}O(n log n) time and O(1) space: it meets the space rule. But there's a way that uses the order even better.
See it in a diagram
Put L on the smallest value and R on the largest, and look at their sum:
- too small:
L's value is too small to pair with anything, because even the largest value wasn't enough. MoveLright. - too big:
R's value is too big to pair with anything, because even the smallest value was too much. MoveRleft. - equal: done.
Each step throws away one value for good, so the walk takes at most n - 1 steps.
Spot the pattern
Sorted input + looking for a pair → two pointers from both ends. The sorted order is what makes it work: it tells you, after one sum, which of the two values can be discarded.
Compare with Two Sum:
| Two Sum (unsorted) | Two Sum II (sorted) | |
|---|---|---|
| Tool | hash map | two pointers |
| Time | O(n) | O(n) |
| Extra space | O(n) | O(1) |
Same speed, but the sorted version needs no memory. That's the whole point of this station: when the data is sorted, two pointers usually replace a hash map.
The optimal solution
lo = 0,hi = n - 1.- While
lo < hi:s = numbers[lo] + numbers[hi];- if
s == target, return[lo + 1, hi + 1]; - if
s < target,lo += 1; elsehi -= 1.
Code in 6 languages
Each program runs the three examples from the top.
#include <cstdio>
#include <vector>
using namespace std;
vector<int> twoSumSorted(const 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}; // 1-indexed
if (s < target) lo++; // too small: the left value must grow
else hi--; // too big: the right value must shrink
}
return {};
}
int main() {
vector<pair<vector<int>, int>> tests = {{{2, 7, 11, 15}, 9}, {{2, 3, 4}, 6}, {{-1, 0}, -1}};
for (auto& [numbers, target] : tests) {
vector<int> r = twoSumSorted(numbers, target);
printf("[");
for (size_t i = 0; i < numbers.size(); i++) printf(i ? ", %d" : "%d", numbers[i]);
printf("], target %d -> [%d, %d]\n", target, r[0], r[1]);
}
}import java.util.*;
public class Main {
static int[] twoSumSorted(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}; // 1-indexed
if (s < target) lo++; // too small: the left value must grow
else hi--; // too big: the right value must shrink
}
return new int[0];
}
public static void main(String[] args) {
int[][] arrays = {{2, 7, 11, 15}, {2, 3, 4}, {-1, 0}};
int[] targets = {9, 6, -1};
for (int t = 0; t < arrays.length; t++)
System.out.println(Arrays.toString(arrays[t]) + ", target " + targets[t] + " -> "
+ Arrays.toString(twoSumSorted(arrays[t], targets[t])));
}
}def two_sum_sorted(numbers, target):
lo, hi = 0, len(numbers) - 1
while lo < hi:
s = numbers[lo] + numbers[hi]
if s == target:
return [lo + 1, hi + 1] # 1-indexed
if s < target:
lo += 1 # too small: the left value must grow
else:
hi -= 1 # too big: the right value must shrink
return []
tests = [([2, 7, 11, 15], 9), ([2, 3, 4], 6), ([-1, 0], -1)]
for numbers, target in tests:
print(f"{numbers}, target {target} -> {two_sum_sorted(numbers, target)}")function twoSumSorted(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]; // 1-indexed
if (s < target) lo++; // too small: the left value must grow
else hi--; // too big: the right value must shrink
}
return [];
}
const tests = [[[2, 7, 11, 15], 9], [[2, 3, 4], 6], [[-1, 0], -1]];
for (const [numbers, target] of tests)
console.log(`[${numbers.join(", ")}], target ${target} -> [${twoSumSorted(numbers, target).join(", ")}]`);package main
import (
"fmt"
"strings"
)
func twoSumSorted(numbers []int, target int) []int {
lo, hi := 0, len(numbers)-1
for lo < hi {
s := numbers[lo] + numbers[hi]
if s == target {
return []int{lo + 1, hi + 1} // 1-indexed
}
if s < target {
lo++ // too small: the left value must grow
} else {
hi-- // too big: the right value must shrink
}
}
return nil
}
func main() {
tests := []struct {
numbers []int
target int
}{{[]int{2, 7, 11, 15}, 9}, {[]int{2, 3, 4}, 6}, {[]int{-1, 0}, -1}}
list := func(a []int) string { return strings.ReplaceAll(fmt.Sprint(a), " ", ", ") }
for _, t := range tests {
fmt.Printf("%s, target %d -> %s\n", list(t.numbers), t.target, list(twoSumSorted(t.numbers, t.target)))
}
}static int[] TwoSumSorted(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[] { lo + 1, hi + 1 }; // 1-indexed
if (s < target) lo++; // too small: the left value must grow
else hi--; // too big: the right value must shrink
}
return Array.Empty<int>();
}
var tests = new (int[] numbers, int target)[] { (new[] { 2, 7, 11, 15 }, 9), (new[] { 2, 3, 4 }, 6), (new[] { -1, 0 }, -1) };
foreach (var (numbers, target) in tests)
Console.WriteLine($"[{string.Join(", ", numbers)}], target {target} -> [{string.Join(", ", TwoSumSorted(numbers, target))}]");All six print:
[2, 7, 11, 15], target 9 -> [1, 2]
[2, 3, 4], target 6 -> [1, 3]
[-1, 0], target -1 -> [1, 2]
- With values between -1000 and 1000, a sum can't overflow, so plain
intis fine everywhere.
Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Brute force: every pair | O(n²) | O(1) |
| Binary search for each partner | O(n log n) | O(1) |
| Hash map (Two Sum) | O(n) | O(n): breaks the rule |
| Two pointers | O(n) | O(1) |
Why it never skips the answer
Suppose the answer is the pair at positions a < b. The pointers start outside or on them: lo <= a and hi >= b. Could lo move past a before hi reaches b? lo only moves right when the sum is too small. While lo is at a and hi is still right of b, numbers[hi] >= numbers[b], so the sum is at least the target, never too small. So lo waits at a. The same argument keeps hi from moving past b. Both pointers end on the answer.
Edge cases and common mistakes
- Returning 0-indexed positions: the most common wrong answer here. Add one.
- Duplicates:
[1, 2, 2, 4]with target 4 gives[2, 3]; the pointers handle equal values naturally. - Negative numbers: the logic doesn't care about sign, only about order.
lo <= hiinstead oflo < hi: that lets an element pair with itself.- Reaching for a hash map anyway: it works, but it ignores the O(1) space requirement. An interviewer will notice.
Where it's used in real apps
- Merge joins in databases: when both tables are sorted on the join key, the database walks one pointer down each, advancing whichever is smaller. It's the same "the order tells you which pointer moves" logic, and it needs no hash table.
- Merging sorted lists: the merge step of merge sort, and merging sorted logs from several servers, walk pointers by comparing the values under them.
- Price matching: in a sorted fare list, finding two fares closest to a budget walks in from both ends, exactly like this.
Quick quiz
1. The sum is too small. Why is it safe to move
L, and not R?
Even paired with the largest remaining value (R), L's value falls short, so L can't be in any answer. Moving R left would only make the sum smaller.
2. Why does this need O(1) space when Two Sum needed O(n)?
The sorted order already gives you the information the hash map stored: which partner could still work. Two indexes are enough.
3. What would you change to find the pair whose sum is
closest to the target?
Keep the same walk, track the sum with the smallest |sum - target|, and don't stop at equality unless it's exact. Still O(n).
4. What does the binary-search version cost, and when might you prefer it?
O(n log n) time, O(1) space. Rarely better here, but the idea (search the sorted rest for a partner) helps when you can't move two pointers, for example when the partner must come from a different sorted list.
Solved it yourself and understood the optimal approach? Mark it to track your progress.