Facebook Pixel
Recursion Interview Questions in JavaScript

What is memoization in recursion in JavaScript?

The answer

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).

More FAQs in Recursion Interview Questions in JavaScript

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.

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.

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.