Design terminating recursive algorithms
Quick answer
A recursive algorithm solves a problem by calling itself on smaller subproblems. It needs a base case and a progress measure that eventually reaches that case.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function sum(n) { if (n === 0) return 0; return n + sum(n - 1);}console.log(sum(4),sum(0));Expected console output:
10 0The base returns zero; pending additions unwind to ten.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function countCalls(n) { if (n === 0) return 1; return 1 + countCalls(n - 1);}console.log(countCalls(3));Expected console output:
4There are calls for 3, 2, 1 and 0.
How it works and cost model
For a bounded nonnegative integer n, define a base case before recursive calls. For sum(n), the subproblem is sum(n - 1), and n decreases toward zero. In typical JavaScript runtimes each pending call uses stack space; a long recursion may exceed the available stack. The example has O(n) time and O(n) active frames. A loop can compute the same sum with constant auxiliary scalar space. Recursion is particularly helpful for trees and divide-and-conquer problems.
Common mistakes
A base case that is never reachable does not guarantee termination. Validate input boundaries and do not rely on tail-call optimization being available.
Practice
Implement sum of array values using an index that advances toward length. Compare the number of calls with a loop and test the empty array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Design terminating recursive algorithms — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
Which condition proves progress for sum(n) on nonnegative integers?
Why can recursion fail on very large input in JavaScript even when mathematically terminating?
For sum(n) with one pending call per smaller n, what auxiliary stack space is modeled?
What is the exact console output in the Recursive algorithm termination example 1?
function sum(n) { if (n === 0) return 0; return n + sum(n - 1);}console.log(sum(4),sum(0));What is the exact console output in the Recursive algorithm termination example 2?
function countCalls(n) { if (n === 0) return 1; return 1 + countCalls(n - 1);}console.log(countCalls(3));