Problem
Given an array of integers
numbersthat is sorted in non-decreasing order, return the indices (1-indexed) of two numbers,[index1, index2], such that they add up totargetandindex1 < index2. You may not use the same element twice. There will always be exactly one valid solution. Your solution must use 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, time. Two Sum I’s hash map gets time, but uses 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 (ifnumbers[left] + numbers[right] > target, thennumbers[right]is too big even with the smallest remaining value), so the answer is never skipped. time, space. - Edge cases to remember: return 1-indexed positions; duplicates (
[1,1], target2); negatives and zeros; the answer can be the two middle elements, so the pointers may travel almost the whole array.while Trueis only safe because a solution is guaranteed;while left < rightis the defensive version.
Solution
Approach A — two pointers from both ends (mine) ✅ best practice
Complexity: Time · Space
This is already the optimal solution: each step moves one pointer inward, so there are at most 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 · Space
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 · Space ❌ breaks the -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 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 : 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 , 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
rightleft; too small → moveleftright. 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 to . - Mistakes I made: none in the algorithm, it’s the optimal solution. Things to keep in
mind:
while Truerelies on the “exactly one solution” guarantee; writewhile 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).