Chat app~18 min2s · 256 MBtarget O(q log n) time, O(q) spacerecursion
The message pipeline of a chat app has five kinds of recursive handlers. A handler gets a size n, and the runtime allows at most limit calls to be open at the same moment. One call past that crashes the worker.
Before a deploy, the team has a list of jobs. Each job is a handler and a size. They want to know which jobs would crash the worker, without running them.
Write over_the_limit(kinds, ns, limit).
i runs the handler kinds[i] on the size ns[i]. The handlers are:| Handler | Rule |
|---|---|
countdown |
with n == 0 it returns; otherwise it calls countdown(n - 1) |
skip |
with n <= 0 it returns; otherwise it calls skip(n - 2) |
halve |
with n == 0 it returns; otherwise it calls halve(n // 2) |
double |
with n == 0 it returns; otherwise it calls double(n // 2) twice, one after the other |
split |
with n <= 1 it returns; otherwise it calls split(n - 1) and then split(n - 2) |
i, in increasing order, of the jobs whose depth is more than limit.Input: kinds = ["countdown", "skip", "halve", "split", "double"], ns = [3, 10, 100, 5, 6], limit = 5
Output: [1, 2]Take the five jobs and a limit of 5.
| Job | Handler and size | Longest chain of open calls | Depth |
|---|---|---|---|
| 0 | countdown 3 | 3, 2, 1, 0 | 4 |
| 1 | skip 10 | 10, 8, 6, 4, 2, 0 | 6 |
| 2 | halve 100 | 100, 50, 25, 12, 6, 3, 1, 0 | 8 |
| 3 | split 5 | 5, 4, 3, 2, 1 | 5 |
| 4 | double 6 | 6, 3, 1, 0 | 4 |
The depths 6 and 8 are more than 5. Jobs 1 and 2 crash the worker, so the answer is [1, 2].
Input: kinds = ["split"], ns = [1], limit = 1
Output: []The call split(1) returns at once, so its depth is 1. A depth equal to the limit is allowed, so the answer is empty.
Input: kinds = ["countdown", "countdown"], ns = [4, 5], limit = 5
Output: [1]The handler countdown(4) opens 5 calls, which is allowed with a limit of 5. The handler countdown(5) opens 6 calls, which is one too many, so the answer is [1].
1 ≤ kinds.length ≤ 5,000, and ns.length equals kinds.lengthcountdown, skip, halve, double and split0 ≤ ns[i] ≤ 10^15, and for split at most 70 (the problem needs the chain, not a run)1 ≤ limit ≤ 1,000,000A split of size 70 makes about 6 × 10^14 calls, and a countdown of size 10^15 needs 10^15 frames. No job can be run, so the depth must be read from the rule of each handler. The depth is the longest chain of open calls, and that has a formula for each shape.