Two Pointers · Sorted pair

Two Sum II Visualizer

What is Two Sum II

The array is sorted. Find the two values that add up to target and return their 1-based indices. There is exactly one solution, and you may not use the same index twice.

4 9
2 7 11 15
1 2

Approach

A map of complementsA hash map works on an unsorted array. Here the order already tells you which side is too small.
Ends moving inwardIf the sum of the ends is too small, move the left pointer. If it is too large, move the right pointer. A match is the answer.

Interactive solution

L and R, and the sum they make
L, R = 0, n - 1
while L < R:
s = a[L] + a[R]
if s == target: return L + 1, R + 1
if s < target: L += 1
else: R -= 1
no pair
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n)Each step moves one pointer.
MemoryO(1)Only the two indices are stored.

Implementation

def two_sum(a, target):
    l, r = 0, len(a) - 1
    while l < r:
        s = a[l] + a[r]
        if s == target:
            return l + 1, r + 1
        if s < target:
            l += 1
        else:
            r -= 1
    return None