Practice · 02 Sorted Arrays: Two Pointers · 2/5

Two Sum II - Input Array Is Sorted

Two Sum again, but sorted: no hash map needed.

MediumLeetCode #167
Solve on LeetCode ↗

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 numbers sorted in non-decreasing order, find two numbers that add up to target. Return their indices as [index1, index2], with 1 <= index1 < index2. There is exactly one solution, you may not use the same element twice, and your solution must use only constant extra space.

numberstargetOutput
[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 {};
}

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 {};
}

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. Move L right.
  • too big: R's value is too big to pair with anything, because even the smallest value was too much. Move R left.
  • equal: done.
target 15135789111 + 11 = 12too small → L right3 + 11 = 14too small → L right5 + 11 = 16too big → R left5 + 9 = 14too small → L right7 + 9 = 16too big → R left7 + 8 = 15found → [4, 5] (1-indexed)6 steps for 7 numbers · each step discards one value · O(n), O(1) space
Target 15 in [1, 3, 5, 7, 8, 9, 11]. Each sum says which pointer to move: too small moves L right, too big moves R left. After six sums the pointers land on 7 and 8.

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)
Toolhash maptwo pointers
TimeO(n)O(n)
Extra spaceO(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

  1. lo = 0, hi = n - 1.
  2. While lo < hi:
    • s = numbers[lo] + numbers[hi];
    • if s == target, return [lo + 1, hi + 1];
    • if s < target, lo += 1; else hi -= 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]);
    }
}

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 int is fine everywhere.

Time and space complexity

ApproachTimeExtra space
Brute force: every pairO(n²)O(1)
Binary search for each partnerO(n log n)O(1)
Hash map (Two Sum)O(n)O(n): breaks the rule
Two pointersO(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 <= hi instead of lo < 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.