What is the time complexity of recursive fibonacci in JavaScript?
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]; ... }.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Recursive Problems and Solutions in JavaScript
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).
Still have questions?
Browse all our FAQs or reach out to our support team
