Music streaming app~25 min2s · 256 MBtarget O(n × len(steps)) time, O(n) spacedp
A music app plays a queue of n songs. A jump rule lets the player move forward by any of a few jump sizes. A recursion counts the ways to reach the end of the queue.
The team wants to know, before it adds a cache, whether a cache will help. That depends on how often the recursion asks the same question again.
Your team lead says: For a queue and its jump sizes, tell me the calls without a cache, the different inputs, and the calls with a cache.
Write cache_report(n, steps).
m makes one call. Then, for every jump size step in steps with step ≤ m, it makes a call for m - step. A call for 0 makes no more calls.m. A call whose input is already stored returns at once, and it still counts as a call. Any other call is stored after its calls are made.n.n.Input: n = 4, steps = [1, 2]
Output: [12, 5, 8]The inputs are 4, 3, 2, 1 and 0, so there are 5 different inputs. The cached recursion calls each different input once in full.
| Call | Input | What happens |
|---|---|---|
| 1 | 4 | not stored: calls 3 and 2 |
| 2 | 3 | not stored: calls 2 and 1 |
| 3 | 2 | not stored: calls 1 and 0 |
| 4 | 1 | not stored: calls 0 |
| 5 | 0 | not stored: no calls |
| 6 | 0 | stored: returns at once |
| 7 | 1 | stored: returns at once |
| 8 | 2 | stored: returns at once |
The plain recursion makes 12 calls, the cached one makes 8, and there are 5 different inputs. The answer is [12, 5, 8].
Input: n = 10, steps = [6, 7]
Output: [3, 3, 3]With jump sizes 6 and 7, the recursion for 10 calls 4 and 3, and those have no step that fits. No input repeats, so a cache saves nothing. The answer is [3, 3, 3].
Input: n = 20, steps = [1, 2, 3]
Output: [266079, 21, 58]With jump sizes 1, 2 and 3 for 20, the plain recursion makes 266,079 calls for only 21 different inputs. The cache needs 58 calls.
1 ≤ n ≤ 501 ≤ steps.length ≤ 50, and 1 ≤ steps[i] ≤ 50With every jump size from 1 to 50, the plain recursion for 50 makes 1,125,899,906,842,624 calls, which is 2^50. Running it is not possible, so the plain count comes from a table. The answer is below 2^53, so it is exact in every language.