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).
How do you implement fibonacci with memoization in JavaScript?
More FAQs in Recursion Interview Questions 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 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).
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.