awelgorithms

Map equality is key and value

Updated

Both sides of each pair count. Same keys with different values are not equal. Same values under different keys are not equal. {4:2} is not {2:4}. Frequency maps that differ by one count are not equal.

What to focus on

Identity (same object) is stronger than equality. Two separately built maps with the same pairs are equal and not identical.

Worked examples

swap

a = [4] as {4:2}, b = {2:4}
  1. keys {4} vs {2}

Result: false

same keys

a = [4, 1] as {4:2,1:8}, b = {4:2, 1:0}
  1. key 1 differs

Result: false

same pairs

a = [4, 1] as {4:2,1:8}, b = {1:8, 4:2}
  1. keys and values match

Result: true

Try it

Write equal(a, b). a and b are hash maps. Return true only when every key and every value match. Swapped key and value is false. Same pairs in another order is true. a = [4] as {4:2}, b = {2:4} → false. a = [4, 1] as {4:2,1:8}, b = {4:2, 1:0} → false. a = [4, 1] as {4:2,1:8}, b = {1:8, 4:2} → true.

maps are non-empty. Keys and values are integers.