Bank app~25 min2s · 256 MBtarget O(n + output) time, O(n + output) spaceclassic twin: lc-113tree-recursion
A bank app shows a household budget as a tree. The top line is the whole budget. Each line splits into at most two smaller lines, a left one and a right one, and a line with no smaller lines is a last line. Every line has an amount, and some are credits, which are negative.
Your team lead wants every route from the top line to a last line whose amounts add up to a target, so the app can highlight them.
Write budget_routes(values, left, right, target).
0 to n - 1, and line 0 is the top. An empty budget has three empty lists.values[i] is the amount of line i. left[i] and right[i] are the numbers of its smaller lines, or -1 where there is none.0, follows smaller lines, and ends at a last line. Its total is the sum of the amounts of every line on it.target. A route is the list of its amounts from the top down. Order the routes by their last lines, from left to right. Where two routes first differ, the one that turns left comes first.Input: values = [5, 3, 4, 1, 2, 0], left = [1, 3, 5, -1, -1, -1], right = [2, 4, -1, -1, -1, -1], target = 9
Output: [[5, 3, 1], [5, 4, 0]]Line 0 (amount 5) splits into 1 (amount 3) and 2 (amount 4). Line 1 splits into 3 (amount 1) and 4 (amount 2). Line 2 has only a left line 5 (amount 0).
Keep the route so far and its total. Add a line when you arrive, and take it off when you leave. The left side is tried first.
| Arrive at | Route so far | Total | Last line? | What happens |
|---|---|---|---|---|
0 |
[5] |
5 | no | go on |
1 |
[5, 3] |
8 | no | go on |
3 |
[5, 3, 1] |
9 | yes | equals 9: save a copy |
4 |
[5, 3, 2] |
10 | yes | not 9 |
2 |
[5, 4] |
9 | no | go on: not a last line |
5 |
[5, 4, 0] |
9 | yes | equals 9: save a copy |
Input: values = [5, 4], left = [1, -1], right = [-1, -1], target = 5
Output: []The only route is [5, 4], with a total of 9. Line 0 alone is not a route, because it is not a last line.
Input: values = [], left = [], right = [], target = 0
Output: []0 ≤ length of values = length of left = length of right ≤ 10^5-1000 ≤ values[i] ≤ 1000left and right is -1 or a line number from 1 to n - 10-10^9 ≤ target ≤ 10^910^6 amounts in totalA budget can be one chain of 100,000 lines. Copying the route so far at every line costs about n^2 / 2 steps on it. Calls that wait for each other would also be 100,000 deep, which is more than Python allows by default.
Keep one route list, add and remove lines as you go, and copy it only when a route matches. Use a loop, not nested calls.