progress

~/problems / Arrays & hashing / Hash maps and counting

Design HashMap

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

The Monster Vault is a row of buckets. Hash a monster's name to a bucket number to store it there, and hash again to find it. Two names can share a bucket (a collision), so each bucket keeps a short list.

Build MonsterVault with MonsterVault(), put(name, power) (store or update), get(name) (the power, or -1) and remove(name) (does nothing if absent).

v = MonsterVault()
v.put("OGRE", 40)
v.put("GOB", 7)
v.put("LICH", 90)    # GOB and LICH may share a bucket: that's fine
v.get("LICH")        # 90
v.get("ORC")         # -1
v.put("GOB", 12)     # GOB is already there: update it
v.get("GOB")         # 12
v.remove("OGRE")
v.get("OGRE")        # -1
  • No built-in hash map or set (dict, set, unordered_map, HashMap, ...). Lists of buckets and a ready-made string hash like hash(name) are fine. The tests can't check this: building the buckets is the exercise.
  • Names are 1 to 12 uppercase letters; powers are in [0, 10^9].
  • ⭐ Bonus: a speed test with 40,000 monsters earns a star if calls stay O(1) on average: when buckets get too full, double the row and spread everyone out.
Show hint

summing letter values (A = 1, ...) makes many names collide; h = h * 31 + letter spreads them much better.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc