Monitoring~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1137recursion
A monitoring system retries a failed health check. The number of retries it schedules at attempt n is the sum of the retries scheduled at the three attempts before it.
Attempt 0 schedules 0 retries, and attempts 1 and 2 schedule 1 retry each. The on-call team plans for up to 50 attempts.
Your team lead says: How many retries are scheduled at attempt
n? The dashboard must answer at once.
Write retry_counts(attempt).
Input: attempt = 4
Output: 4The recursion asks for the three attempts below. It stores each answer for an attempt of 3 or more.
| Attempt | Retries | How it is found |
|---|---|---|
| 0 | 0 | base case |
| 1 | 1 | base case |
| 2 | 1 | base case |
| 3 | 2 | attempts 2, 1 and 0: 1 + 1 + 0 |
| 4 | 4 | attempts 3, 2 and 1: 2 + 1 + 1 |
The cached recursion makes 7 calls, where the plain one makes 7. The answer is 4.
Input: attempt = 0
Output: 0Attempt 0 is a base case. It schedules no retries, so the answer is 0.
Input: attempt = 25
Output: 1389537Attempt 25 schedules 1,389,537 retries, which fits in a 32-bit integer.
0 ≤ attempt ≤ 50At attempt 50 the answer is 5,742,568,741,225, which is above 2^32 and below 2^53, so use a 64-bit integer. The plain recursion makes 11,160,088,646,113 calls. The cached recursion makes 145.