Engineering platform~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-100tree-recursion
You work on the engineering platform behind an app. Each build ships its settings menu as a tree. Every menu entry has an id, and at most two sub-entries: a left one and a right one.
Before a release, you check that the menu in the new build is the same as the menu in the old build. The two menus are stored with different entry numbers, so you cannot compare them entry by entry.
Write same_menu(values_a, left_a, right_a, values_b, left_b, right_b).
values_a, left_a and right_a. Menu B is stored in values_b, left_b and right_b.0 to n - 1, and entry 0 is the top entry. An empty menu has three empty lists.values_a[i] is the id of entry i. left_a[i] and right_a[i] are the numbers of its left and right sub-entries, or -1 where there is none. Menu B works the same way.true when the two menus have the same shape and, in every place, the same id. A sub-entry on the left is not the same as one on the right. Return false otherwise.Input: values_a = [10, 20, 30, 40], left_a = [1, 3, -1, -1], right_a = [2, -1, -1, -1], values_b = [10, 30, 20, 40], left_b = [2, -1, 3, -1], right_b = [1, -1, -1, -1]
Output: trueMenu A has entry 0 (id 10) at the top, with a left sub-entry 1 (id 20) and a right sub-entry 2 (id 30). Entry 1 has a left sub-entry 3 (id 40). Menu B has the same tree, with the entries numbered in a different order.
| Pair (entry in A, entry in B) | Ids | Left pair | Right pair |
|---|---|---|---|
| (0, 0) | 10 and 10 match |
(1, 2) | (2, 1) |
| (2, 1) | 30 and 30 match |
none in both | none in both |
| (1, 2) | 20 and 20 match |
(3, 3) | none in both |
| (3, 3) | 40 and 40 match |
none in both | none in both |
Every pair matched, so the answer is true.
Input: values_a = [5], left_a = [-1], right_a = [-1], values_b = [5, 7], left_b = [1, -1], right_b = [-1, -1]
Output: falseMenu B has a left sub-entry that menu A does not have.
Input: values_a = [], left_a = [], right_a = [], values_b = [], left_b = [], right_b = []
Output: trueTwo empty menus are the same.
0 ≤ length of values_a = length of left_a = length of right_a ≤ 10^5, and the same for menu B0 ≤ values_a[i], values_b[i] ≤ 10^6left_a, right_a, left_b and right_b is -1 or an entry number from 1 to n - 10A menu can be a chain of 100,000 entries. Describing every entry by the full path from the top costs about n^2 / 2 steps on a chain. Calls that wait for each other would also be 100,000 deep, which is more than Python allows by default.
Walk both menus in step, and look at each entry once. Keep the pairs still to check in a list, not in nested calls.