Skip to the solution
EasyDSA9 min read

What is recursion and what is a base case?

682 views

The problem

Question presented to candidate: "What is recursion, and what is a base case? Write a small recursive function in Python β€” say factorial or the sum of a list β€” point to the base case, and tell me what happens if it is missing."

What a strong answer should cover:

  • Recursion: a function that solves a problem by calling itself on a smaller instance of the same problem.
  • The base case: the smallest input, answered directly without another call; the recursive case: reduces the problem and calls itself.
  • Every call must make progress toward the base case; a missing or unreachable base case recurses until the stack overflows.
  • The call stack: calls wind down to the base case, then results unwind back up; stack space is the maximum depth, time is the number of calls times the work per call.
  • Python specifics: a missing base case ends in RecursionError (default limit 1000), recursing on slices copies data, and functools.lru_cache memoises a recursion in one line.

Code / implementation expected: Yes β€” a short recursive Python function (factorial, sum, palindrome) with its base case, and its cost.

  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTrace factorial(4): calls going down, returns coming back up
PythonFive small recursions, each with its base case
PythonBase-case bugs, and naive vs memoised Fibonacci

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 21 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is a binary search tree (BST)?

Continue