Skip to content
Back to notes
Oct 16, 2026
Medium

Two Sum II - Input Array Is Sorted

sorted array + pair with a target sum → two pointers from both ends. Sum too big → move right left; too small → move left right. The sorting is what makes each move safe (it rules out every pair using the discarded value), and it replaces the hash map, so space drops from O(n) to O(1).
  • array
  • two pointers
  • binary search

Problem

Given an array of integers numbers that is sorted in non-decreasing order, return the indices (1-indexed) of two numbers, [index1, index2], such that they add up to target and index1 < index2. You may not use the same element twice. There will always be exactly one valid solution. Your solution must use O(1)O(1) additional space.

Example 1

Input:  numbers = [1,2,3,4], target = 3
Output: [1,2]

1 + 2 = 3; with 1-indexing that’s [1, 2].

Constraints

  • 2 <= len(numbers) <= 30000
  • -1000 <= numbers[i] <= 1000
  • -1000 <= target <= 1000

Thinking

  • Brute force idea: try every pair i < j, O(n2)O(n^2) time. Two Sum I’s hash map gets O(n)O(n) time, but uses O(n)O(n) space, which this version forbids.
  • Key insight: the array is sorted. Put one pointer at each end and look at the sum: too big → the only way to shrink it is right -= 1; too small → left += 1. Each step discards a value that can’t be in any valid pair (if numbers[left] + numbers[right] > target, then numbers[right] is too big even with the smallest remaining value), so the answer is never skipped. O(n)O(n) time, O(1)O(1) space.
  • Edge cases to remember: return 1-indexed positions; duplicates ([1,1], target 2); negatives and zeros; the answer can be the two middle elements, so the pointers may travel almost the whole array. while True is only safe because a solution is guaranteed; while left < right is the defensive version.

Solution

Approach A — two pointers from both ends (mine) ✅ best practice

Complexity: Time O(n)O(n) · Space O(1)O(1)

This is already the optimal solution: each step moves one pointer inward, so there are at most n−1n-1 steps, and only two indices are stored.

def two_sum_sorted(numbers: list[int], target: int) -> list[int]:
    left = 0
    right = len(numbers) - 1

    while True:  # safe only because a solution is guaranteed; `while left < right` otherwise
        total = numbers[left] + numbers[right]
        if total > target:
            right -= 1
        elif total < target:
            left += 1
        else:
            return [left + 1, right + 1]

Approach B — binary search for the complement

Complexity: Time O(nlog⁡n)O(n \log n) · Space O(1)O(1)

For each i, binary-search target - numbers[i] in the part after i (using bisect’s lo/hi bounds, so no slice is copied). Also meets the space limit, but slower than two pointers because each search starts from scratch instead of reusing what the last step learned.

from bisect import bisect_left


def two_sum_sorted_bsearch(numbers: list[int], target: int) -> list[int]:
    n = len(numbers)
    for i in range(n - 1):
        need = target - numbers[i]
        j = bisect_left(numbers, need, i + 1, n)
        if j < n and numbers[j] == need:
            return [i + 1, j + 1]

Approach C — hash map (Two Sum I), ignores the sorting

Complexity: Time O(n)O(n) · Space O(n)O(n) ❌ breaks the O(1)O(1)-space rule

The Two Sum I solution: remember each value’s index and look up the complement. Correct, but it doesn’t use the sorted order and stores up to nn entries.

def two_sum_sorted_hashmap(numbers: list[int], target: int) -> list[int]:
    seen = {}  # value -> 1-based index; this is the O(n) extra space
    for j, x in enumerate(numbers, start=1):
        if target - x in seen:
            return [seen[target - x], j]
        seen[x] = j

Scratch / Experiments

Worst case for two pointers: the answer is the two middle elements of a max-length array (30000), so left walks ~15000 steps right and right walks ~15000 steps left.

Measured (one run): two pointers ~1.1 ms, binary search ~1.7 ms, hash map ~0.66 ms. The hash map wins on time here even though everything is O(n)O(n): it stops after ~15000 iterations (when it reaches the 2), while two pointers makes ~30000 loop steps, and a dict lookup in C costs about as much as one Python comparison. It still loses on the actual requirement: it holds ~15000 dict entries, vs two integers. Binary search is only ~1.5× slower than two pointers despite the extra log⁡n\log n, because each bisect_left runs in C.

half = 15000
numbers = [-1000] * (half - 1) + [1, 2] + [1000] * (half - 1)
target = 3
for fn in (two_sum_sorted, two_sum_sorted_bsearch, two_sum_sorted_hashmap):
    assert fn(numbers, target) == [half, half + 1]
%timeit two_sum_sorted(numbers, target)
%timeit two_sum_sorted_bsearch(numbers, target)
%timeit two_sum_sorted_hashmap(numbers, target)

Takeaways

  • Pattern: sorted array + pair with a target sum → two pointers from both ends. Sum too big → move right left; too small → move left right. The sorting is what makes each move safe (it rules out every pair using the discarded value), and it replaces the hash map, so space drops from O(n)O(n) to O(1)O(1).
  • Mistakes I made: none in the algorithm, it’s the optimal solution. Things to keep in mind: while True relies on the “exactly one solution” guarantee; write while left < right (and return something after the loop) when that guarantee isn’t given. Don’t forget the 1-indexed output.
  • Related problems: Two Sum (#1, unsorted → hash map), 3Sum (#15, sort, fix one number, then this two-pointer scan), 4Sum (#18, two fixed numbers + two pointers), 3Sum Closest (#16, same scan, track the nearest sum), Container With Most Water (#11, two pointers from both ends, move the shorter side), Valid Palindrome (#125, two pointers moving inward), Two Sum IV - Input is a BST (#653, inorder traversal = sorted).