Recursion Interview Questions in JavaScript
Common recursion interview questions with solutions.
Recursion Interview Questions
Q1: Implement factorial.
function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); }
Q2: Implement fibonacci with memoization.
const memo = {}; function fib(n) { if (n < 2) return n; if (memo[n]) return memo[n]; return memo[n] = fib(n - 1) + fib(n - 2); }
Q3: Flatten a nested array.
function flatten(arr) { return arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []); }
Q4: Traverse a DOM tree.
function traverseDOM(node, callback) { callback(node); node.children.forEach(child => traverseDOM(child, callback)); }
Q5: Implement a countdown.
function countdown(n) { if (n < 0) return; console.log(n); countdown(n - 1); }
The Takeaway
Recursion interview questions: factorial (base case + n * recurse), fibonacci with memoization (cache results), flatten (reduce + recurse on arrays), DOM traversal (recurse on children), and countdown (base case + recurse with n-1).
const memo = {}; function fib(n) { if (n < 2) return n; if (memo[n]) return memo[n]; return memo[n] = fib(n-1) + fib(n-2); }. Memoization reduces time from O(2^n) to O(n).
function flatten(arr) { return arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []); }. If an item is an array, recurse. Otherwise, concatenate.
function traverseDOM(node, callback) { callback(node); Array.from(node.children).forEach(child => traverseDOM(child, callback)); }. Call the callback on the current node, then recurse into each child.
Caching the results of expensive recursive calls. Before computing, check if the result is in the cache. If so, return it. This prevents redundant computation. For fibonacci, it reduces time from O(2^n) to O(n).
O(2^n) - exponential. Each call makes two recursive calls, creating a binary tree of calls. Many calls are redundant (fib(3) is computed multiple times). Memoization reduces this to O(n).
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

