awelgorithms

Store a map of maps

Updated

A map of maps is an outer key whose value is another map. First time you see the outer key, put a fresh inner map. Later writes go to that inner map. The outer size is the number of outer keys, not the number of leaves.

What to focus on

Graphs (u to v to weight), grouping then indexing, and 2D sparse tables use this. First get(outer, u) returning missing means there is no inner map yet. Create it on the write path.

Worked examples

two edges from 4

a = [], put (4,1)→2 then (4,9)→3
  1. outer 4 created once
  2. inner {1:2, 9:3}

Result: {4:{1:2, 9:3}} · outer size 1

second outer

a = [4] already {4:{1:2, 9:3}}, put (1,9)→8
  1. new outer key 1

Result: {4:{1:2, 9:3}, 1:{9:8}} · outer size 2

empty

a = []
  1. no outer keys

Result: {}

Try it

Write putNested(m, u, v, w). m is the outer map. u is the outer key. v is the inner key. w is the leaf value. If m has no inner map for u, create one. Then put v to w in that inner map. Return m. Do not print. a = [], put (4,1)→2 then (4,9)→3 → {4:{1:2, 9:3}} · outer size 1. a = [4] already {4:{1:2, 9:3}}, put (1,9)→8 → {4:{1:2, 9:3}, 1:{9:8}} · outer size 2. a = [] → {}.

outer and inner keys are integers. Start from {} and apply the listed puts.