awelgorithms

Compare two frequency maps

Updated

Two bags are equal iff their frequency maps are equal: same keys, same counts. Lengths differing already forbids equality. Treat absent as 0. Do not require both maps to store zeros.

What to focus on

You can build both maps, or increment one array and decrement the other (need all zeros / empty at the end).

Worked examples

same bags

a = [1, 4, 1], b = [4, 1, 1]
  1. {1:2, 4:1} both

Result: true

different counts

a = [1, 1, 4], b = [1, 4, 4]
  1. 1:2 vs 1:1

Result: false

extra key

a = [1, 4], b = [1, 4, 9]
  1. b has 9

Result: false

Try it

Write sameBag(a, b). a and b are arrays of integers. Return true if their frequency maps match: same keys, same counts. a = [1, 4, 1], b = [4, 1, 1] → true. a = [1, 1, 4], b = [1, 4, 4] → false. a = [1, 4], b = [1, 4, 9] → false.

a and b are non-empty lists of integers.

LeetCode problems that use this skill