Countdown Timer with a Safe Recursion Base Case

Hard ⏱ 18 min 29% acceptance ★★★★★ 4.7
Implement countdown(n) that recursively builds and returns a list of integers counting down from n to 0 (inclusive), e.g. countdown(3) -> [3, 2, 1, 0]. Add explicit guard clauses so it never runs away: raise ValueError immediately (without recursing) if n is negative, and also raise ValueError if n > 900 since Python's default recursion limit is around 1000 and this would otherwise crash with an unhelpful RecursionError.

Examples

Example 1
Input
countdown(3)
Output
[3, 2, 1, 0]
Explanation

Counts down one step per recursive call.

Example 2
Input
countdown(-1)
Output
ValueError raised
Explanation

Guard clause rejects negative input before recursing.

Constraints

  • Raise ValueError for n < 0 or n > 900, checked before any recursive call.

Topics

RecursionError Handling

Companies

DeloitteJPMorgan Chase

Hints

Hint 1

Put both guard checks at the very top of the function, before the base/recursive cases.

Hint 2

Base case for the countdown itself: n == 0 returns [0].

Hint 3

Recursive case: [n] + countdown(n - 1).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.