Map a value to its first index
Updated
Left-to-right: put if absent. Later repeats do not overwrite. First-seen index is the value you keep. This is put-if-absent, not put.
What to focus on
Two-sum sometimes wants the first index of the complement. After the pass, missing values have no key.
Worked examples
repeat keeps first
a = [4, 1, 9, 1]- 1→1 stays
- do not write 3
Result: {4:0, 1:1, 9:2}
all unique
a = [4, 1, 9]- each put-if-absent writes
Result: {4:0, 1:1, 9:2}
empty
a = []- no indices
Result: {}
Try it
Write firstIndex(a). a is an array of integers. Put value→index if absent. Later repeats do not overwrite. Return the map. a = [4, 1, 9, 1] → {4:0, 1:1, 9:2}. a = [4, 1, 9] → {4:0, 1:1, 9:2}. a = [] → {}.
a is a list of integers and may be empty.