Skip to content
mlmentorship

Two Sum

Return the indices of two numbers that add to the target.

Published · 4 min read ·Core ·Foundation

30-second answer map

Visual first · depth when needed

Check each complement before saving the current value.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Two Sum

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Return the indices of two numbers that add to the target.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Two Sum: Check each complement before saving the current value.

Input and goalReturn the indices of two numbers that add to the target.
Initialize the lookupBefore index 0, seen is empty; the only retained state will map each scanned value to its index.
current i=030214273
examplenums = [3, 2, 4, 7], target = 6target6mapLabelseen: value -> index
seen: value -> indexempty

Recognize it
The prompt asks for two positions whose values satisfy a target sum, so each current value determines one exact complement that can be looked up.
Keep true
Before processing index i, seen contains exactly the useful values from indices below i; therefore a hit is an earlier, distinct element.
Reuse it
When a current item determines one exact missing partner, store only prior facts needed to recognize that partner; this transfers to complement, difference, and prefix-sum lookup problems.
Read it this way: Before index 0, seen is empty; the only retained state will map each scanned value to its index. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Hash map.

Simple idea: For each number, calculate the number it needs. If that needed number was seen earlier, the pair is complete. Check first, then save the current number. This avoids using the same item twice.

def two_sum(nums: list[int], target: int) -> list[int]:
   seen: dict[int, int] = {}
   for index, num in enumerate(nums):
      needed = target - num
      if needed in seen:
         return [seen[needed], index]
      seen[num] = index
   return []

Cost: time and space.