Online store~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-110tree-recursion
An online store shows its categories as a menu tree. Every category has at most two sub-categories, a left one and a right one. Shoppers reach a product by opening one category after another.
Your team lead wants the menu kept balanced, so that no part of it is much deeper than the rest. A menu is balanced when, in every category, the two sub-menus differ in depth by at most one level.
Write is_menu_balanced(left, right).
0 to n - 1, and category 0 is the top of the menu. An empty menu has two empty lists.left[i] and right[i] are the numbers of the sub-categories of category i, or -1 where there is none.0. A category with no sub-categories has depth 1.true when, in every category, the depths of its left and right sub-menus differ by at most 1. Return false otherwise. An empty menu is balanced.Input: left = [1, 3, 5, 4, -1, -1, -1], right = [2, -1, 6, -1, -1, -1, -1]
Output: falseCategory 0 has the sub-categories 1 and 2. Category 1 has only a left sub-category 3, and 3 has only a left sub-category 4. Category 2 has the sub-categories 5 and 6.
The categories are checked from the bottom up. The depth of a category is one plus the deeper of its two sub-menus.
| Category | Left depth | Right depth | Difference | Result |
|---|---|---|---|---|
4 |
0 | 0 | 0 | depth 1 |
6 |
0 | 0 | 0 | depth 1 |
5 |
0 | 0 | 0 | depth 1 |
3 |
1 (category 4) |
0 | 1 | depth 2 |
2 |
1 | 1 | 0 | depth 2 |
1 |
2 (category 3) |
0 | 2 | too deep: not balanced |
Category 1 has a left sub-menu two levels deep and no right sub-menu. The answer is false, even though the top category alone looks fine: its two sides are 3 and 2 levels deep.
Input: left = [1, -1, -1], right = [2, -1, -1]
Output: trueOne category with two sub-categories, each with none, is balanced.
Input: left = [1, 2, -1], right = [-1, -1, -1]
Output: falseA chain of three: the top category has a left sub-menu of depth 2 and no right sub-menu.
0 ≤ length of left = length of right ≤ 10^5left and right is -1 or a category number from 1 to n - 10A menu can be a chain of 100,000 categories. Asking a category for its depth by walking everything below it, for every category, costs about n^2 / 2 steps on a chain. Calls that wait for each other would be 100,000 deep, which is more than Python allows by default.
Work out each depth once, from the bottom, and reuse it. Use a loop and a list instead of nested calls.