06

Algorithms for Frontend

Trees, recursion, memoization, debounce

GoalBuild the algorithmic toolkit that actually shows up in frontend work: recursion over trees, memoization, debounce/throttle, and recognizing O(n²) smells.

Lessons

Trees are everywhere in frontend

The DOM is a tree. The React component tree is a tree. JSON is a tree. File systems are trees. Recursion is how you traverse them.

js
function traverse(node) {
  visit(node);                           // do something
  for (const child of node.children) {
    traverse(child);                     // recurse
  }
}

This single pattern: count nodes, find a node, transform a tree, render nested comments.

Complexity: O(n) — each node visited once.

DFS vs BFS

Same algorithm, one swap: stack (pop) vs queue (shift).

js
// DFS — goes deep first (uses stack)
function dfs(root) {
  const stack = [root];
  while (stack.length) {
    const node = stack.pop();     // LIFO
    visit(node);
    stack.push(...node.children);
  }
}

// BFS — goes wide first (uses queue)
function bfs(root) {
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();   // FIFO
    visit(node);
    queue.push(...node.children);
  }
}

Choose BFS when: finding the NEAREST match (closest to root). Choose DFS when: exploring paths, rendering trees, checking existence.

Memoization

Cache a function's results so repeated calls with the same input are instant. Uses a closure to keep the cache alive.

js
function memoize(fn) {
  const cache = new Map();         // closure keeps this alive
  return function(arg) {
    if (cache.has(arg)) return cache.get(arg);
    const result = fn(arg);
    cache.set(arg, result);
    return result;
  };
}

This is the foundation of useMemo, useCallback, and React.memo. The dependency array IS the cache key.

Debounce vs Throttle

Both control how often a function runs — using closures + timers.

Debounce — wait until events STOP for Xms, then fire once. Use case: autocomplete search (wait until typing stops).

Throttle — fire at most once per Xms, regardless of event count. Use case: scroll handler, resize handler.

js
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

function throttle(fn, limit) {
  let waiting = false;
  return (...args) => {
    if (waiting) return;
    fn(...args);
    waiting = true;
    setTimeout(() => { waiting = false; }, limit);
  };
}

Challenges3

Write working code. Run to see output. Check to grade.

CH1
Count all tree nodes
Warm-up

Write countNodes(node) that counts every node in a tree where each node has a children array.

js
const tree = { id:1, children: [
  { id:2, children: [] },
  { id:3, children: [{ id:4, children:[] }] }
]};
countNodes(tree) // → 4
JavaScript
CH2
Find node by id
Medium

Write findNode(root, id) that returns the node with the matching id, or null if not found.

JavaScript
CH3
Memoize fibonacci
Hard

Without memoization, fib(40) makes ~1 billion calls (O(2ⁿ)). Write a memoized version that makes ~40 calls (O(n)).

console.log(fib(40)) should log 102334155.

JavaScript

References