1688. Same Bag of Bags

Two warehouses record their stock as nested lists: integers are item codes and sub-lists are crates that can hold more codes and more crates. Order does not matter anywhere, since crates can be shuffled freely.

Call first and second equivalent when, at the top level and recursively inside every crate, their integers match as multisets (same values, same multiplicities) and their sub-lists can be paired one-to-one so that each pair is equivalent. Return true if the two structures are equivalent and false otherwise. Building a canonical form bottom-up, where a list's form is its children's forms sorted and joined, makes the comparison a string equality. Expect roughly O(n * depth * log n) time and O(n * depth) space.

Example 1

Input:
first = [1,[2,3]], second = [[3,2],1]
Output:
true
Explanation:

The inner lists [2, 3] and [3, 2] are the same bag and the outer integers match, so they are equivalent.

Example 2

Input:
first = [1,[2]], second = [1,[3]]
Output:
false
Explanation:

The sub-lists hold different integers, so the structures are not equivalent.

Example 3

Input:
first = [[1],[1]], second = [[1],[2]]
Output:
false
Explanation:

The first has two sub-lists [1] but the second has [1] and [2], which cannot be paired up.

Constraints

Each structure has at most 1000 integers and lists; nesting depth ≤ 50; -104 ≤ value ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n * depth * log n)
Space
O(n * depth)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…