awelgorithms

Compare two hash maps

Updated

Equal maps have the same size and, for every key in either map, the same value. Iteration order does not matter. Size mismatch is an early false.

What to focus on

Compare by walking one map and get-or-miss on the other, then check sizes so extra keys on the other side fail. Do not compare only a few keys.

Worked examples

equal unordered

a = [4, 1, 9] as {4:2,1:8,9:3}, b = {1:8, 9:3, 4:2}
  1. same pairs

Result: true

value differs

a = [4, 1, 9] as {4:2,1:8,9:3}, b = {4:2, 1:0, 9:3}
  1. key 1 is 8 vs 0

Result: false

empty

a = [], b = []
  1. both empty

Result: true

Try it

Write equal(a, b). a and b are hash maps of key to value. Return true if they have the same size and the same value for every key. Order does not matter. a = [4, 1, 9] as {4:2,1:8,9:3}, b = {1:8, 9:3, 4:2} → true. a = [4, 1, 9] as {4:2,1:8,9:3}, b = {4:2, 1:0, 9:3} → false. a = [], b = [] → true.

Either map may be empty. Keys and values are integers.