progress

~/problems / Two pointers

Two Sum II

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

A sorted bridge of numbered stones leads to the boss's gate, which opens for two stones adding up to exactly target. Two knights start on the first and last stones, with no room to write anything down.

Write find_stones(stones: list[int], target: int) -> list[int] that returns the two positions [i, j], counting from 1, with i < j. Exactly one pair works.

find_stones([2, 5, 9, 13, 17, 21, 26, 34, 37, 44], 50)   # [4, 9]   (13 + 37)
find_stones([3, 3, 8], 6)                                # [1, 2]
find_stones([-4, 1, 6, 10], 2)                           # [1, 3]   (-4 + 6)

Up to 2 * 10^5 stones. Use O(1) extra space: no set or map (the tests measure memory). ⭐ Bonus: a speed test earns a star in O(n).

Show hint

add the knights' stones. If the sum is too small, can the left stone ever be in the answer?

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc