Write a recursive function that returns the integers from n down to 1 in
order. If n is 0 or negative, return an empty slice.
countdown(n)
Aim to solve it without a loop — let the recursion build the slice.
countdown(3) // → [3, 2, 1]
countdown(1) // → [1]
countdown(0) // → []
This is a good first recursion problem because the loop version is so familiar: iterate from n down to 1, appending each number. Recursion solves the same problem without a loop, by having the function call itself on a smaller input. The goal isn't a clever trick — it's practicing the two-part shape every recursive function has: a base case that stops it, and a recursive case that shrinks the problem and calls again.
What's the smallest version of this problem you already know the answer to? If n is 0 or negative, there's nothing to count down — the answer is an empty list. That's the base case, and it's essential: without it, the function would call itself forever, eventually running out of stack space.
If you already had the correct countdown for n-1 (the list n-1, n-2, ..., 1), the countdown for n is just that list with n stuck on the front. You don't need to know how countdown(n-1) works internally — trust that it's correct, and handle only the one new piece: putting n at the front.
That trust is the key mental leap in recursion: assume the recursive call does its job correctly for smaller input, and only worry about combining your current step with the result.
Calling countdown(3) doesn't produce anything right away — it calls countdown(2), which calls countdown(1), which calls countdown(0). That last call hits the base case and returns an empty list immediately. Now the calls unwind in reverse: countdown(1) gets the empty list back and returns [1]. countdown(2) gets [1] and returns [2, 1]. countdown(3) gets [2, 1] and returns [3, 2, 1]. Each call adds one number to the front on its way back out — n calls deep, so O(n) time and O(n) space (one stack frame per pending call).
A loop would actually be more efficient here (no call-stack overhead). The point of this exercise is to internalize the base-case/recursive-case pattern before applying it to problems where a loop doesn't work as naturally — trees, nested structures, and search spaces where recursion is the more natural fit.
def countdown(n):
if n <= 0:
return []
return [n] + countdown(n - 1)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.