awelgorithms

Prove a map copy does not share storage

Updated

After copy, put or delete on b must leave a identical. Shared backing means b.put(k,v) is visible in a. Check that b is not the same object as a, then mutate b and re-read a.

What to focus on

Shallow copy of map-of-lists still shares the lists. That fails the no-share test for nested mutation even when put of a new key is independent.

Worked examples

independent put

a = [4, 1, 9] as {4:2,1:8,9:3}, b = copy(a), put b 7→5
  1. a has no 7

Result: no share

alias

a = [4, 1, 9] as {4:2,1:8,9:3}, b = a, put b 7→5
  1. a now has 7

Result: shared — fail

empty

a = [], b = copy(a), put b 4→2
  1. a still {}

Result: no share

Try it

Write copyIndependent(a). a is a hash map. Copy a into b, then mutate b. Return whether a is unchanged. Alias b=a must fail. Shallow list values still share storage. a = [4, 1, 9] as {4:2,1:8,9:3}, b = copy(a), put b 7→5 → no share. a = [4, 1, 9] as {4:2,1:8,9:3}, b = a, put b 7→5 → shared — fail. a = [], b = copy(a), put b 4→2 → no share.

keys are integers. The original may be empty.