awelgorithms

Do not assume map iteration order

Updated

Hash maps are unordered unless the language documents insertion-order. Algorithm problems must not rely on first key is the smallest after a hash put.

What to focus on

If you need sorted keys, sort them. If you need first-seen order, store a list alongside the map. Tests that pass because the hash was lucky will fail on another runtime.

Worked examples

not sorted

a = [9, 1, 4] as keys
  1. iteration might be 9,1,4 or 1,4,9

Result: do not claim sorted

not array order

a = [4, 1, 9]
  1. buckets scramble

Result: not necessarily 4 then 1 then 9

empty

a = []
  1. no order to assume

Result: {}

Try it

Write keys(m). m is the hash map. Print keys. Do not claim sorted order or array order. Sort explicitly when you need 1, 4, 9. a = [9, 1, 4] as keys → do not claim sorted. a = [4, 1, 9] → not necessarily 4 then 1 then 9. a = [] → {}.

keys are integers. Empty is in the cases.