Algorithms
Recursion
This depends on the problem. But each call still waiting to finish uses stack space (memory that tracks paused calls) — O(depth) space.
The idea, in plain English
Recursion is when a function calls itself to solve a smaller version of the same problem. Think of Russian nesting dolls. To open the biggest one, you open the next, then the next, until you reach the tiniest doll that opens no further. That last step is called the 'base case'.
How it works
- 1Define the base case: the smallest input where you stop and return a direct answer.
- 2Otherwise, call the function again with a smaller input.
- 3Combine that smaller answer with the current step to build the full result.
When you'd use it
Use it for problems that naturally break into smaller copies of themselves: walking a tree or folder structure, divide-and-conquer sorts, and many math definitions.
Common beginner mistakes
- Forgetting the base case, so the function calls itself forever and crashes with a 'stack overflow'.
- Not making the input smaller on each call, which also never ends.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
5! = 120
0! = 1See it in motion
Press play. We compute factorial(5) by calling a smaller copy of itself each time.
Not sure this is the right topic? See the learning paths → or where this leads →