Search~18 min2s · 256 MBtarget O(q log n) time, O(1) spacerecursion
The index builder of a search engine handles a shard of n postings with a recursive function. A call on one posting does 1 unit of work and stops. A call on more postings scans all of them, which is n units of work.
After the scan, the call calls itself branches times, each on the first n // 2 postings. Different versions of the builder use 1, 2 or 3 branches. Before a release, the team wants the total work of each shard size.
Write halving_costs(sizes, branches).
n postings is 1 when n <= 1. Otherwise it is n plus the work of branches calls on n // 2 postings each.n in sizes, return the total work of the call on n postings, counting every call below it.Input: sizes = [8], branches = 2
Output: [32]Take n = 8 and branches = 2. The recursion tree has one level for each halving.
| Level | Calls | Size of each | Work of the level |
|---|---|---|---|
| 1 | 1 | 8 | 8 |
| 2 | 2 | 4 | 8 |
| 3 | 4 | 2 | 8 |
| 4 | 8 | 1 | 8 |
Every level does 8 units of work. There are 4 levels, so the total is 32.
Input: sizes = [1, 2, 3], branches = 1
Output: [1, 3, 4]With one branch each call has one child, so the work is a sum of halves. Size 1 gives 1, size 2 gives 2 + 1 = 3, and size 3 gives 3 + 1 = 4, because 3 // 2 is 1.
Input: sizes = [10, 100], branches = 3
Output: [70, 2743]Three branches make the calls grow by 3 at each level while the size halves, so the work of a level grows by 1.5 times. Size 10 gives 70 and size 100 gives 2,743.
1 ≤ sizes.length ≤ 1,0001 ≤ sizes[i] ≤ 1,000,000,0001 ≤ branches ≤ 3With two branches, a shard of 10^9 postings makes 1,073,741,823 calls, and with three branches it makes 102,945,566,047,324. The tree has about 30 levels. Each level has a known number of calls of one size, so we can add up the levels and never run the calls.