Skip to the page

Frontend-flavoured problems · senior

Virtual DOM diff and keyed list reconciliation

A virtual DOM diff compares two trees of plain objects with cheap rules—different type means replace the subtree, same type means patch props and diff children—and keys let it match list items so only items that really moved are moved.

The notes

What you must know

  • VNode = { type, props, children }; text nodes are strings. A full tree edit distance is O(n³), so frameworks use O(n) heuristics.
  • Rule 1: different type (div → span, or a different component) → unmount the old subtree and mount the new one (state is lost).
  • Rule 2: same type → diff props: set changed/new ones, remove missing ones; event props update listeners.
  • Children without keys are matched by index: inserting at the start makes every item 'change' and moves state to the wrong item (the index-as-key bug).
  • Keyed children: build oldKey → index; reuse matches, remove missing, create new; to move the fewest nodes, keep the longest increasing subsequence of old indices in place (Vue 3/Inferno); React instead walks once with lastPlacedIndex and moves items that went backwards.
  • Minimum moves = (number of kept keys) − (LIS length of their old indices in new order).
  • Then commit to the real DOM in a batch; React additionally splits work into fiber units it can pause (concurrent rendering).

The red pen

Common traps: mistake → fix

  • Mistake: The virtual DOM is always faster than the DOM

    Fix: it adds work; it wins by batching and avoiding needless writes.

  • Mistake: Index keys are fine if items have no state

    Fix: reorders still re-render everything and break inputs, focus and animations.

  • Mistake: Same position + same type keeps state even if the key changed

    Fix: a different key forces a remount.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the virtual DOM and why use it?
  2. Walk me through how two trees are diffed. What happens when the type changes?
  3. Why are keys needed? Show the index-as-key bug.
  4. Given old and new key orders, how many moves are needed at minimum?
  5. Implement a small render-to-string or createElement.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview