awelgorithms

Tiny alphabet is an array

Updated

If keys are dense in a tiny range — 0..m, or 'a'..'z' as 0..25 — an array indexed by the key beats a hash map: true O(1), no hash, no collision chain, missing is a stored 0.

What to focus on

Use a hash when keys are sparse, huge (10^9), negative without a shift, or an unknown object type. int[26] for lowercase. Map for unicode or arbitrary ints.

Worked examples

letters

kind = "letters", data = "abca"
  1. cnt[s[i]-'a']++
  2. 26 slots

Result: array, not a map

sparse huge

kind = "huge", data = [4, 10^9, 1]
  1. cannot allocate f[10^9+1]

Result: hash map {4:1, 1000000000:1, 1:1}

digits empty

kind = "digits 0..9", data = []
  1. f of zeros

Result: array of 0s

Try it

Write countWith(kind, data). kind is "letters", "huge", or "digits". data is the string or array to count. Use int[26] for letters, a hash map for huge sparse keys, and f[10] when keys are 0..9. kind = "letters", data = "abca" → array, not a map. kind = "huge", data = [4, 10^9, 1] → hash map. kind = "digits 0..9", data = [] → array of 0s.

Letter keys are 'a'..'z'. Integer keys are in the stated domain.