Recursive Problems and Solutions in JavaScript
Common recursive problems with solutions: factorial, fibonacci, tree, flatten.
Recursive Problems and Solutions
Factorial
function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); }
Fibonacci
function fib(n) { if (n < 2) return n; return fib(n - 1) + fib(n - 2); }
Flatten Nested Arrays
function flatten(arr) { return arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []); }
Tree Traversal (DFS)
function traverse(node, callback) { callback(node); if (node.children) node.children.forEach(child => traverse(child, callback)); }
Power
function power(base, exp) { if (exp === 0) return 1; return base * power(base, exp - 1); }
Reverse String
function reverse(str) { if (str.length <= 1) return str; return reverse(str.slice(1)) + str[0]; }
The Takeaway
Common recursive problems: factorial (n * factorial(n-1)), fibonacci (fib(n-1) + fib(n-2)), flatten (reduce + concat), tree traversal (forEach + recurse), power (base * power(base, exp-1)), and reverse string (recurse on slice + first char).
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 traverse(node, callback) { callback(node); if (node.children) node.children.forEach(child => traverse(child, callback)); }. Call the callback on the current node, then recurse into each child.
function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); }. Base case: 1 returns 1. Recursive case: n * factorial(n-1).
function reverse(str) { if (str.length <= 1) return str; return reverse(str.slice(1)) + str[0]; }. Take the first character, reverse the rest, and append the first character at the end.
O(2^n) - exponential. Each call makes two recursive calls, creating a binary tree of calls. Use memoization to reduce to O(n): const memo = {}; function fib(n) { if (n in memo) return memo[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.

