Skip to content
mlmentorship

Two Sum

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

Published · 21 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

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

ML breadth · closed-book attempt

Two Sum

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

Problem

Input. An integer list nums and an integer target. Output. Return two zero-based indices [i, j] such that nums[i] + nums[j] == target. Rules. The indices must differ; one position cannot supply both numbers. Values may be negative or repeated, and the list may be empty. Return any valid pair in either order, not the values or every pair. Return [] if no pair exists. Leave nums unchanged. Example. For nums = [3, 2, 4, 7] and target = 6, return [1, 2]. Those positions contain 2 and 4. For [3] and target 6, return [], not [0, 0].

08:00recommended time

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

30-second answer map

Check each complement before saving the current value.

Problem trace

Look up the complement before storing the current index

Worked example: lookup before insertion prevents pairing an item with itselfFor target 6 and input (3,3), the first 3 cannot match itself. The second 3 finds the earlier index 0 and returns distinct indices.The query sees only the earlierstate; insertion happens afterwardIndex 0: query complement 3 first3emptyNo earlier partner; only then store 3-> index zero.Index 1: query complement 3 first33:0Found earlier index 0; return 0,1.
Read it this way: For target 6 and input (3,3), the first 3 cannot match itself. The second 3 finds the earlier index 0 and returns distinct indices. Could index zero incorrectly match itself if its three were stored before the first lookup?
Full interview answer 21 min read
Reading depth

Find two input positions whose values add to one requested target sum.

Problem

Input. An integer list nums and an integer target.

Output. Return two zero-based indices [i, j] such that nums[i] + nums[j] == target.

Rules. The indices must differ; one position cannot supply both numbers. Values may be negative or repeated, and the list may be empty. Return any valid pair in either order, not the values or every pair. Return [] if no pair exists. Leave nums unchanged.

Example. For nums = [3, 2, 4, 7] and target = 6, return [1, 2]. Those positions contain 2 and 4. For [3] and target 6, return [], not [0, 0].

Picture: Query Before Saving

Problem trace

Separate three-value input: lookup complement before storing its current index

Input and goalReturn the indices of two numbers that add to the target.
Initialize the lookupBefore index 0, seen is empty. Each retained value maps to one earlier index.
Complement lookup at index 0: NEXT LOOKUPThe indexed input is 3, 2, 4, 7, target 6. Needed equals 6 minus 3, or 3. No earlier entries are saved yet.. Dashed new map rows are inserted only after a failed lookup.nums; target = 63index 0i = 02index 14index 27index 36 - 3 = 3seen: before saving currentvaluesaved indexemptyNEXT LOOKUPonly priorindices countNo earlier entries are saved yet.
Checkpoint map after storage or before the next query; storage is not a successful lookup.CURRENT i=0; value=36-3=3BEFORE THE QUERYempty->no earlier indicesStore for a later index, never itself.
current i
0
example
nums = [3, 2, 4, 7], target = 6
target
6

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.
Before index 0, seen is empty. Each retained value maps to one earlier index. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the answer [1,2]? Why can index 0 not pair with itself?
Reference drawing

Problem trace

Look up the complement before storing the current index

Worked example: lookup before insertion prevents pairing an item with itselfFor target 6 and input (3,3), the first 3 cannot match itself. The second 3 finds the earlier index 0 and returns distinct indices.The query sees only the earlierstate; insertion happens afterwardIndex 0: query complement 3 first3emptyNo earlier partner; only then store 3-> index zero.Index 1: query complement 3 first33:0Found earlier index 0; return 0,1.
Execution trace
Input and goalReturn the indices of two numbers that add to the target.
Initialize the lookupBefore index 0, seen is empty. Each retained value maps to one earlier index.
Complement lookup at index 0: NEXT LOOKUPThe indexed input is 3, 2, 4, 7, target 6. Needed equals 6 minus 3, or 3. No earlier entries are saved yet.. Dashed new map rows are inserted only after a failed lookup.nums; target = 63index 0i = 02index 14index 27index 36 - 3 = 3seen: before saving currentvaluesaved indexemptyNEXT LOOKUPonly priorindices countNo earlier entries are saved yet.
Checkpoint map after storage or before the next query; storage is not a successful lookup.CURRENT i=0; value=36-3=3BEFORE THE QUERYempty->no earlier indicesStore for a later index, never itself.
current i
0
example
nums = [3, 2, 4, 7], target = 6
target
6

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.
Before index 0, seen is empty. Each retained value maps to one earlier index. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the answer [1,2]? Why can index 0 not pair with itself?
Read it this way: For target 6 and input (3,3), the first 3 cannot match itself. The second 3 finds the earlier index 0 and returns distinct indices. Could index zero incorrectly match itself if its three were stored before the first lookup?
indexnumneededseen before queryResult
033{}Save 3: 0
124{3: 0}Save 2: 1
242{3: 0, 2: 1}Return [1, 2]

Before each query, seen represents earlier values with strictly earlier indices. One index per value suffices for one witness. Overwriting after a miss preserves that guarantee. The trace’s i is the code’s index.

Code

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 []

Expected time is under usual dictionary/unit-cost arithmetic assumptions; auxiliary space is .

[3], target 6, returns []; [3, 3] returns [0, 1].

Change 1: Count Index Pairs

New task. Count distinct unordered index pairs.

Picture and change. Store prior frequencies; query before incrementing.

Code.

def count_pairs(nums, target):
   counts = {}
   answer = 0
   for value in nums:
      answer += counts.get(target - value, 0)
      counts[value] = counts.get(value, 0) + 1
   return answer

Check. [3, 3, 3], target 6, adds 0, 1, 2: total 3. A single 3 gives 0.

Use when. Multiplicity matters without emitting indices.

Change 2: Emit Every Pair

New task. Return all original-index witnesses.

Picture and change. Keep every earlier matching index, not one representative.

Code.

def all_pairs(nums, target):
   seen = {}
   answer = []
   for index, value in enumerate(nums):
      for earlier in seen.get(target - value, []):
         answer.append([earlier, index])
      seen.setdefault(value, []).append(index)
   return answer

Check. [3, 3, 3], target 6, returns [[0, 1], [0, 2], [1, 2]].

Use when. Every witness is required.

Failure: Saving Before Querying

Store-first logic lets the lone 3 in [3] match itself. Query order enforces distinctness.

Transfer Check

Why may the reference overwrite repeated values but all_pairs may not?

Reasoned Answer

One earlier witness suffices for the reference. Enumeration must retain every matching position.

Output Size Changes the Cost

The counting variant retains expected time and auxiliary space. For returned pairs, enumeration takes expected time and total space, including output. All-equal input can produce pairs; no algorithm can materialize them in linear output space.

Empty input yields no witness, zero count and an empty enumeration. Sorting changes position tracking and needs a different movement proof; it is not a drop-in replacement for this contract. Compare prefix counting when stored objects become range boundaries rather than item positions.