Skip to the solution
HardLow-Level DesignAsked in 20247 min read

Virtual DOM diff algorithm

2.7k views

The problem

Problem, as an interviewer would state it: "Implement diff(oldNode, newNode) for a simple virtual DOM — comparing two vnode trees and producing a minimal, TARGETED set of patches, not a full re-render of everything."

Examples:

Code
diff(oldTree, newTreeWithOneChangedLabel);
// a targeted UPDATE patch deep inside the tree, not a full REPLACE at the root

Clarifying questions expected:

  • Should genuinely identical subtrees produce NO patch at all, to avoid unnecessary real DOM work later?
  • What should happen when the TAG NAME itself changes between old and new — a targeted update, or a full replace?
  • Does the diff need to handle a real, changing number of children, not just changes within existing ones?

Code / implementation expected: Yes — real, direct proof across 5 scenarios: identical trees producing no patch, a targeted nested text update, a targeted props update, a root-level tag-change replace, and the CREATE/REMOVE cases.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the diff algorithm correctly produces no patch for identical trees, a targeted nested UPDATE for a deep text change, and a full REPLACE for a tag-name change

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 134 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Flatten a Deeply Nested Array Iteratively (No Recursion, No Call-Stack Limit)

Continue