Group indices per value
Updated
Value → list of indices where it appears. This is the grouping you want when the problem asks every index of 1, not just first or last.
What to focus on
Build in one left-to-right pass so lists are sorted. Empty lists are absent keys, not stored.
Worked examples
repeats
a = [4, 1, 9, 1]- 4→[0]
- 1→[1,3]
- 9→[2]
Result: {4:[0], 1:[1,3], 9:[2]}
all same
a = [7, 7, 7]- 7→[0,1,2]
Result: {7:[0,1,2]}
empty
a = []- no indices
Result: {}
Try it
Write indexLists(a). a is an array of integers. Return value → list of indices, built left to right so lists are increasing. a = [4, 1, 9, 1] → {4:[0], 1:[1,3], 9:[2]}. a = [7, 7, 7] → {7:[0,1,2]}. a = [] → {}.
a is a list of integers and may be empty.