awelgorithms

Overwrite is the grouping bug

Updated

put(k, x) where you meant put(k, list+x) leaves only the last item. The map still looks correctly keyed and tests on unique keys pass. Always store a collection if several values share a key.

What to focus on

Frequency ++ is a scalar update, not grouping. Grouping must append. If you see size == distinct keys but lists of length 1 for known repeats, you overwrote.

Worked examples

bug

a = [4, 1, 9, 1], put value→index each time
  1. 1→1 then 1→3 overwrites

Result: {4:0, 1:3, 9:2} last index only

fix

a = [4, 1, 9, 1], append indices
  1. 1→[1,3]

Result: {4:[0], 1:[1,3], 9:[2]}

unique ok

a = [4, 1, 9], put value→index
  1. no repeats
  2. overwrite never fires

Result: {4:0, 1:1, 9:2} happens to work

Try it

Write indexLists(a). a is an array of integers. Append indices under each value. Do not put value→index on repeats. Unique keys hide the overwrite bug. a = [4, 1, 9, 1], put value→index each time → {4:0, 1:3, 9:2} last index only. a = [4, 1, 9, 1], append indices → {4:[0], 1:[1,3], 9:[2]}. a = [4, 1, 9], put value→index → {4:0, 1:1, 9:2} happens to work.

a is a non-empty list of integers.