Music streaming app~20 min2s · 256 MBtarget O(q log n) time, O(q) spacecomplexity
A video app rebuilds its "similar titles" lists every night. The job reads the whole catalogue of n titles and runs three phases. The planning team gives it a budget of simple steps for each region's catalogue.
The team asks one question per region. What is the largest catalogue the job can process within that region's budget? You will answer every region exactly, without running the job.
Write largest_catalogue(budgets).
The job on a catalogue of n titles runs these three phases, one after the other. Each step is one simple step.
def nightly_job(n):
for a in range(n): # phase 1: read each title
step()
for a in range(n): # phase 2: compare each title with every later title
for b in range(a + 1, n):
step()
m = n
while m > 1: # phase 3: rounds that halve m, each over all titles
m //= 2
for a in range(n):
step()budgets[i], find the largest whole n >= 0 whose job makes at most budgets[i] steps.Input: budgets = [100, 1000]
Output: [11, 39]Count the three phases for a few sizes. Phase 1 makes n steps, phase 2 makes n(n-1)/2, and phase 3 makes n for each of floor(log2 n) rounds.
| n | Phase 1 | Phase 2 | Phase 3 | Total |
|---|---|---|---|---|
| 11 | 11 | 55 | 33 | 99 |
| 12 | 12 | 66 | 36 | 114 |
| 13 | 13 | 78 | 39 | 130 |
| 14 | 14 | 91 | 42 | 147 |
A catalogue of 11 titles costs 99 steps and fits 100. A catalogue of 12 costs 114 and does not, so the first answer is 11. The same count gives 39 for a budget of 1,000.
Input: budgets = [0, 1, 4, 5]
Output: [0, 1, 1, 2]One title costs 1 step, and two titles cost 5: 2 reads, 1 comparison and 2 for one halving round.
Input: budgets = [1000000]
Output: [1403]1,403 titles cost 998,936 steps, and 1,404 titles cost 1,000,350.
0 ≤ budgets.length ≤ 100,000 (regions)0 ≤ budgets[i] ≤ 10^12 (steps)The answer can reach about 1.4 million titles. Trying every size from 0 upward costs over a million checks for one region, and there are up to 100,000 regions. The step counts reach 10^12, so they need 64-bit integers.