Identical Immutable Subtrees
MediumTrees · Jane Street
An immutable tree library lets nodes be shared, so the structure is a forest in which a node may have several parents (a DAG with no cycles).
nodes describes every node as [node_id, value, children]:
node_idis a unique string.valueis a string label.childrenis an ordered list of child ids. Every child id appears innodes, and the same child may appear more than once.
Two nodes are structurally identical when they have the same value, the same number of children, and their i-th children are structurally identical for every i. Child order matters, and node ids do not.
Return every group of two or more structurally identical nodes:
- each group is a list of node ids sorted in ascending string order,
- groups are sorted by their first id,
- return
[]if no two nodes are identical.
Be careful: because nodes are shared, writing out a subtree in full can be exponentially long, and the structure can be very deep.
Example 1
- Input:
- nodes = [["r", "+", ["x", "y"]], ["x", "*", ["a", "b"]], ["y", "*", ["c", "d"]], ["a", "1", []], ["b", "2", []], ["c", "1", []], ["d", "2", []]]
- Output:
- [["a", "c"], ["b", "d"], ["x", "y"]]
- Explanation
- Leaves
aandcboth hold1, andbanddboth hold2. That makesxandyidentical too, since each is*over a1leaf followed by a2leaf. The rootris the only+node, so it is in no group.
Example 2
- Input:
- nodes = [["p", "f", ["m", "n"]], ["q", "f", ["n", "m"]], ["m", "1", []], ["n", "2", []]]
- Output:
- []
- Explanation
pandqhave the same value and the same children, but in a different order, so they are not identical. The leaves have different values, so there are no groups.
Example 3
- Input:
- nodes = [["top", "T", ["s", "s"]], ["s", "L", []], ["other", "L", []]]
- Output:
- [["other", "s"]]
- Explanation
sis shared and listed twice undertop. It matchesother, a separate leaf with the same value, so they form one group sorted as"other"before"s".
Constraints
1 <= nodes.length <= 10^5- The total number of entries across all
childrenlists is at most2 * 10^5 1 <= value.length <= 10- The child links contain no cycles