DSA Factory
Free Arrays lessonsArrays · Stage 5 · Two pointers · Step 1

Pair sum in a sorted array

Walk inward from both ends. About 8 minutes.

Two fingers, walking towards each other

You have a sorted list of prices and a gift card worth exactly 10. Which two items use it up exactly?

Put one finger on the cheapest item and one on the most expensive, and add them. Too much? The expensive one has to go, so move the right finger one step left. Too little? The cheap one has to go, so move the left finger one step right. Keep going until the two prices add up to 10.

Sum too small? move the left finger right.
Sum too big? move the right finger left.
Walk through ittarget = 10
1
0
3
1
4
2
6
3
8
4
11
5
leftright

1 + 11 = 12 is too big, so right moves one step left.

Move 1 of 5

Why every move is safe

When the sum is too big, the right-hand item can't be in the answer. Even paired with the cheapest item left, it's too much, so pairing it with anything else is worse. You can drop it for good. The same goes for the left item when the sum is too small.

So every move rules out one item forever, and after at most n moves you're done. Checking every pair instead would take about n × n.

Every move: rules out one item for good.
So it's fast: at most n moves, not n × n.
In code
left, right = 0, len(nums) - 1
while left < right:
    total = nums[left] + nums[right]
    if total == target:
        return [left, right]
    if total < target:
        left += 1
    else:
        right -= 1
Quick check

The sum is 12 and the target is 10. Which finger moves?

1, 3, 4, 6, 8, 11 · left finger on 1, right finger on 11
  1. AThe left finger, one step right
  2. BThe right finger, one step left
  3. CBoth fingers
Show the answer

The right finger, one step left. The sum is too big, so swap the 11 for something smaller.

Your problem

Pair sum in a sorted array

You get numbers sorted from smallest to largest, and a target. Return the positions of the two numbers that add up to the target. There is always exactly one answer.

Example
nums = [1, 3, 4, 6, 8, 11], target = 10 → [2, 3]

2 ≤ n ≤ 1,000,000 · sorted ascending · exactly one answer

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve