Payments app~12 min2s · 256 MBtarget O(n log s) time, O(1) spacerecursion
A payments app adds up the entries of a day's settlement ledger with a recursive function, so that two workers can share the job.
The function is total(n), and it takes a block of n entries. For one entry, it reads it and returns. Otherwise it splits the block into a first half of n // 2 entries and a second half of the rest. It calls itself on both halves, and adds the results.
Before a batch run, the operations team wants to know how many calls each block will make, and how deep the stack gets.
Write halving_calls(sizes).
n in sizes, consider the call total(n) described above. It splits n entries into n // 2 and n - n // 2.[calls, deepest] for each size, in order.Input: sizes = [5]
Output: [[9, 4]]Take total(5). The recursion tree has one node for each call.
| Level | Calls on this level | Sizes |
|---|---|---|
| 1 | 1 | 5 |
| 2 | 2 | 2, 3 |
| 3 | 4 | 1, 1, 1, 2 |
| 4 | 2 | 1, 1 |
The 5 entries make 5 leaf calls, and the 4 calls that split make 9 calls in all. The longest path is 5, then 3, then 2, then 1: four calls open at once, so the answer is [9, 4].
Input: sizes = [1]
Output: [[1, 1]]One entry is a leaf. It makes a single call, and the stack holds only that call.
Input: sizes = [2, 3, 8]
Output: [[3, 2], [5, 3], [15, 4]]Two entries make 3 calls, with 2 open at once. Three entries make 5 calls, with 3 open at once. Eight entries make 15 calls, with 4 open at once.
1 ≤ sizes.length ≤ 1,0001 ≤ sizes[i] ≤ 1,000,000,000A block of 10^9 entries makes almost 2 × 10^9 calls. Running the recursion to count them would take minutes. The recursion tree has a fixed shape: every entry is one leaf, and every call that splits has two children. That is enough to count the calls without making them.