awelgorithms

Decide map versus array table

Updated

Dense keys in 0..m with m small: array. Sparse, huge, negative, or object keys: hash map. Offset v-min when the range is small but min ≠ 0. If m is 10^9 and n is 10^5, n wins — use a map.

What to focus on

Arrays give true O(1) and easy 0-defaults. Maps give expected O(1) and store only seen keys. Pick from the key domain, not from habit.

Worked examples

0..9

a = [4, 1, 9, 1], counts
  1. f[10]

Result: array table

10^9

a = [4, 10^9, 1], counts
  1. three keys

Result: hash map

letters

s = "abca"
  1. int[26]

Result: array table

Try it

Write chooseTable(domain). domain is "digits", "huge", or "letters". Return "array" for dense 0..m or 'a'..'z'. Return "map" for huge sparse keys. a = [4, 1, 9, 1], counts → array table. a = [4, 10^9, 1], counts → hash map. s = \"abca\" → array table.

When keys are 0..m, m is small. Huge keys stay sparse. Letters are 'a'..'z'.