Bank app~20 min2s · 256 MBtarget O(top + q × n) time, O(top) spacerecursion
A bank app closes a statement with a recursive rule. A call on n entries is a leaf when n <= 1. Otherwise it calls itself first on n // 2 entries and then on n - 1 entries.
The runtime allows limit calls open at the same moment. On a crash, the engineer needs to know which call was the first one to open past the limit, counting calls in the order they start.
Write first_past_limit(ns, limits).
(ns[i], limits[i]), return the number of the first call with a depth greater than limits[i], or -1 when no call is that deep.Input: ns = [5], limits = [3]
Output: [7]Take n = 5 and limit = 3. List the calls in the order they start.
| Call number | Call | Depth |
|---|---|---|
| 1 | run(5) | 1 |
| 2 | run(2) | 2 |
| 3 | run(1) | 3 |
| 4 | run(1) | 3 |
| 5 | run(4) | 2 |
| 6 | run(2) | 3 |
| 7 | run(1) | 4 |
Call 7 is the first with a depth over 3, so the answer is 7. Calls 3, 4 and 6 are at depth 3, which is allowed.
Input: ns = [1, 2], limits = [1, 1]
Output: [-1, 2]A run on 1 has a single call at depth 1, so a limit of 1 is never passed. A run on 2 calls run(1) second, at depth 2, so call number 2 is past a limit of 1.
Input: ns = [10, 10, 10], limits = [4, 8, 10]
Output: [8, 53, -1]The run on 10 passes a limit of 4 at call 8 and a limit of 8 at call 53. Its deepest call has depth 10, so a limit of 10 is never passed.
1 ≤ ns.length ≤ 1,000, and limits.length equals ns.length1 ≤ ns[i] ≤ 1,0001 ≤ limits[i] ≤ 1,000With n = 1,000 and a limit of 999, the first call past the limit is call number 264,830,889,562. Counting the calls one by one is not possible. But the run has at most 1,000 levels, and skipping a whole subtree needs only its call count.