Python coding

Two positions that hit a target

Given a list of integers nums and an integer target, return [i, j] with i < j such that nums[i] + nums[j] == target. The two positions must be different, though their values may be equal. At most one such pair exists; if there is none, return [].

Aim for one pass over nums.

Besides the tests, one large input (6,000 numbers) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • pair_indices([2,7,11,15], 9) → [0,1]
  • pair_indices([3,2,4], 6) → [1,2]
  • pair_indices([3,3], 6) → [0,1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Each number tells you exactly which partner it needs: target - x. The question is how fast you can ask whether you have seen it.

Hint 2

Walk once with a map from value to index. Look up target - x before you store x, so a number never pairs with itself.

Solution and why it works
pythonO(n) · O(n)
def pair_indices(nums: list[int], target: int) -> list[int]:
    seen = {}
    for j, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], j]
        seen[x] = j
    return []

A map from value to index answers "have I already seen target - x?" in O(1) on average, so one pass replaces the O(n²) check of every pair. Order matters: look up before you store. Storing first lets [5] with target 10 pair the 5 with itself.

Related lab: Loops in motion