call(back)
Algorithms & Data StructuresmediumSign in to star problems

Nested Set Equality

A "nested set" is a collection that can contain integers and/or other nested sets, with no meaningful order and no meaningful duplicates — exactly like a mathematical set. Because sets cannot contain sets in most languages, the input is given as nested lists.

Write a function that determines whether two nested sets are equal.

Examples:

[1, [2, 3]]      vs  [[3, 2], 1]        -> true   (order ignored at every depth)
[1, 1, 2]        vs  [2, 1]             -> true   (duplicates collapse)
[1, [2]]         vs  [1, 2]             -> false  ({2} is not the same as 2)
[[]]             vs  []                 -> false  (a set containing the empty set is not empty)
[[1, 2], [2, 3]] vs  [[2, 3], [1, 2]]   -> true

Hints

Hint 1

Recursively canonicalize each structure bottom-up into a comparable form — one that erases order and duplicates at every depth, then compare the canonical forms.

Hint 2

In JavaScript: map children to canonical strings, collapse duplicates with a Set, sort, and wrap in braces. An integer and a one-element set containing it must stay distinct.

Asked at