Two Sum on a sorted array explained

When the array is already sorted, Two Sum is solved with two pointers: start one at each end, and if their sum is too small move the left one right, if it is too large move the right one left, until the sum hits the target. It runs in O(n) time with O(1) extra space, and the reason it never skips the answer is that each move only discards pairs that provably cannot work.

By Published 7 min read

How the problem is usually posed

You get integers in non-decreasing order and a target value. Exactly one pair of different positions adds up to the target. Return those two positions. Some versions count positions from 1 rather than 0, and many add a rule that you may only use constant extra memory, which is the hint that the hash map from the unsorted version is not what they want this time. The code here returns 0-based indexes; add one to each if the interviewer counts from 1.

Sorted arrays invented for this page
ArrayTargetAnswer (0-based)Check
[1, 3, 4, 8, 13]14[0, 4]1 + 13, found on the first check
[-6, -1, 0, 2, 9]-7[0, 1]-6 + -1
[2, 5, 5, 10]10[1, 2]Equal values at different positions
[0, 3, 7, 14, 20]21[2, 3]7 + 14, found in the middle
Sorted arrays invented for this page. Scroll sideways on a small screen.

Why it is asked after plain Two Sum

The unsorted version rewards trading memory for speed. This version flips the lesson: the input already carries structure, and using that structure removes the need for extra memory. Interviewers want to see whether you notice the sorted order instead of reaching for the dictionary out of habit. They also probe correctness. Converging pointers look like a guess until you explain why a move is safe, and a candidate who can do that clearly tends to handle every later pointer problem well.

Three approaches, slowest first

Every pair

Two nested loops try each pair of positions. O(n²) time, O(1) space. It ignores the sorted order completely, which is the point to make when you mention it.

Binary search for each complement

For each position i, the partner must equal target minus the value at i, and it must sit to the right of i. Because the array is sorted, a binary search over positions i + 1 to the end finds it in O(log n). Over all positions that is O(n log n) time with O(1) space. It is a respectable middle answer and a good way to show you are using the ordering.

from bisect import bisect_left

def partner_search(arr, target):
    for i, x in enumerate(arr):
        want = target - x
        j = bisect_left(arr, want, i + 1)
        if j < len(arr) and arr[j] == want:
            return [i, j]
    return []
Binary search for the partner of each entry, O(n log n).

Converging pointers

Place left on the first index and right on the last. Look at the sum of the two values. If it equals the target, return both indexes. If it is below the target, the only way to grow it is a bigger left value, so step left forward. If it is above, step right back. Stop when the pointers meet.

def sorted_pair(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        total = arr[left] + arr[right]
        if total < target:
            left += 1
        elif total > target:
            right -= 1
        else:
            return [left, right]
    return []
Python: converging pointers, O(n) time, O(1) space.
#include <vector>

std::vector<int> sortedPair(const std::vector<int>& arr, long long target) {
    int left = 0;
    int right = static_cast<int>(arr.size()) - 1;
    while (left < right) {
        long long total = static_cast<long long>(arr[left]) + arr[right];
        if (total < target) {
            ++left;
        } else if (total > target) {
            --right;
        } else {
            return {left, right};
        }
    }
    return {};
}
C++: the same loop. The sum is widened to long long so large values cannot overflow.

Why a move never throws away the answer

Suppose the sum at left and right is too small. Pair the current left value with any partner other than the right one: every such partner sits between the pointers, so it is no larger than the right value, and the sum can only stay too small or shrink. No pair that uses the current left value can reach the target, so discarding it loses nothing. The mirror argument covers a sum that is too large: the current right value is too big to pair with anything still in range.

Put differently, each step removes one whole row or column from the grid of candidate pairs, and it only removes rows or columns that contain no solution. After at most n - 1 steps the pointers meet, so the loop is linear. Saying this in two sentences is often what the interviewer is waiting for.

Comparing the options

n is the array length
MethodTimeExtra spaceUses the sorted order?
Every pairO(n²)O(1)No
Hash map of seen valuesO(n) averageO(n)No
Binary search per entryO(n log n)O(1)Yes
Converging pointersO(n)O(1)Yes
n is the array length. Scroll sideways on a small screen.

Edge cases

  • Fewer than two entries: no pair, so return the agreed empty result.
  • The answer uses equal values, like [2, 5, 5, 10] with target 10. The pointer loop handles it because the two indexes are different.
  • Negative numbers and a negative target.
  • Values near the integer limits in C++, Java or Go, where the sum overflows a 32-bit int. Widen before adding.
  • The answer is the first and last entries, so the loop returns on its first check.
  • No pair exists, if the interviewer drops the guarantee: the pointers meet and you return empty.

Where candidates slip

  • Using left <= right, which can pair an entry with itself.
  • Moving both pointers on a mismatch, which can skip the answer.
  • Reaching for a hash map and missing the constant-space requirement.
  • Returning 0-based indexes when the question counts from 1, or the reverse.
  • Asserting the pointer method works without being able to say why.

Follow-ups worth preparing

  • Count pairs whose sum is at most the target. When the sum fits, every index between left and right also pairs with left, so add right - left and move left.
  • Find the pair whose sum is closest to the target. Same loop, but track the smallest absolute difference instead of stopping on equality.
  • Three entries that hit the target. Fix each entry in turn and run converging pointers on the part to its right, for O(n²) overall.
  • The data is a sorted stream you cannot index backward. Pointers need both ends, so discuss buffering or the hash map instead.

A model explanation

Fictional example

Justifying the pointer moves in a few sentences
Candidate
Because the array is sorted, I can start with the smallest and largest values and steer. If the sum is too small, I need a bigger number, and only moving left forward gives me one.
Interviewer
How do you know you did not skip the answer by moving left?
Candidate
Every remaining partner for that left value is at most the current right value, so all of its sums are too small as well. That value cannot be in the answer. Each move rules out one value safely, so it is linear time and constant memory.

The unsorted original, with the hash map answer, is in Two Sum. Valid Palindrome uses the same inward pair of indexes with a character comparison instead of a sum, and Trapping Rain Water needs a stronger version of this same safety argument to decide which side to move. The coding problems hub lists every walkthrough.

Drilling it with Natively

A useful way to practice this one is to say the safety argument out loud until it is short. Natively transcribes those mock rounds on your Mac or Windows machine, and it can read the problem from a screenshot and suggest an approach you can compare with your own once you finish. See the AI assistant for coding interviews for details.

Questions people ask

How do you solve Two Sum when the input is sorted?

Put one pointer at each end. If the sum is below the target, move the left pointer right; if it is above, move the right pointer left; stop when it matches. That is O(n) time and O(1) extra space.

Why does the two-pointer method not miss the answer?

When the sum is too small, every remaining partner of the left value is no larger than the right value, so none of its pairs can reach the target. Discarding it is safe, and the mirror argument covers a sum that is too large.

Why not use the hash map from regular Two Sum?

It works, but it needs O(n) extra memory and ignores the sorted order. This version is usually asked precisely to see whether you use the ordering to get constant space.

Are the indexes 0-based or 1-based?

It depends on how the problem is posed; some versions count from 1. Ask, and adjust the returned positions.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP