Music streaming app~12 min2s · 256 MBtarget O(n) time, O(1) spacerecursion
A music streaming app shows a countdown before a live launch. A recursive function draws the timer. It shows the seconds left, then calls itself with fewer seconds. When no seconds are left, it shows liftoff and stops.
Several launches run at once, each with its own start value. A tester wants the total of every number a timer shows, so that a log can be checked.
Write launch_totals(starts, step).
show(s). If s <= 0, it shows 0 and returns. Otherwise it shows s and then calls show(s - step).s in starts, return the sum of every number that show(s) shows, including the final 0.show itself. A start of 10^6 with a step of 1 would open a million frames at once.Input: starts = [5, 3], step = 2
Output: [9, 4]Take the start 5 with step 2. Each call shows one number and opens the next call.
| Call | s | Shown | What happens |
|---|---|---|---|
| 1 | 5 | 5 | calls show(3) |
| 2 | 3 | 3 | calls show(1) |
| 3 | 1 | 1 | calls show(-1) |
| 4 | -1 | 0 | base case: shows 0 and returns |
The total is 5 + 3 + 1 + 0 = 9. The start 3 shows 3 and 1, then 0, so its total is 4.
Input: starts = [1], step = 5
Output: [1]The start 1 is already at the end. It shows 1, then calls show(-4), which shows 0. The total is 1.
Input: starts = [10, 10, 7], step = 10
Output: [10, 10, 7]A step as large as the start leaves a single number before the base case. The starts 10, 10 and 7 give 10, 10 and 7.
1 ≤ starts.length ≤ 100,0001 ≤ starts[i] ≤ 1,000,0001 ≤ step ≤ 1,000Running show once for every start would need up to 10^6 frames open at the same time for one timer, and up to 10^11 calls over all timers. Python allows about 1,000 open frames by default. The shown numbers fall by a fixed step, so their sum has a formula and no call is needed.