awelgorithms

Pick an index map when position matters

Updated

A set answers have I seen the complement. It cannot return the other index. If the judge wants indices (or both values at original positions), store value→index.

What to focus on

Value-only two-sum can use a set. Index two-sum cannot. If duplicates matter (two 1s summing to 2), a set still works for existence but the map records which 1.

Worked examples

existence

a = [4, 1, 9], t = 10
  1. set of seen, 9 needs 1

Result: set enough for true

indices

a = [4, 1, 9], t = 10
  1. need index of 1, which is 1

Result: map 1→1, pair (1,2)

empty

a = [], t = 0
  1. no pair

Result: none — set or map both empty

Try it

Write twoSum(a, t). a is an array of integers. t is the target sum. If the judge wants indices, use a value-to-index map, not a set. a = [4, 1, 9], t = 10 → set enough for true. a = [4, 1, 9], t = 10 → map 1→1, pair (1,2). a = [], t = 0 → none — set or map both empty.

a is a list of integers and may be empty. The judge wants indices when the drill says so.