InterviewDB Question · Paris

JSON Difference - Deep Compare Two JSON Objects and Return a Diff

Question Details

Problem

Write a function that compares two JSON-like objects (nested dicts/arrays) and returns a structured diff describing what changed between old and new.

The diff should report:
- "added": keys present in new but not old.
- "removed": keys present in old but not new.
- "modified": keys present in both but with different values (recurse into nested objects).

python
def json_diff(old: dict, new: dict) -> dict:
    ...

Example:

old = {"a": 1, "b": {"x": 10, "y": 20}, "c": 3}
new = {"a": 1, "b": {"x": 99, "z": 30}, "d": 4}

json_diff(old, new) ->
{
  "added":   {"d": 4},
  "removed": {"c": 3},
  "modified": {
    "b": {
      "added":   {"z": 30},
      "removed": {"y": 20},
      "modified": {"x": {"old": 10, "new": 99}}
    }
  }
}

Follow-ups

  1. How do you handle arrays - element-wise comparison, or treat as a whole value?
  2. How would you produce a flat list of JSON Patch (RFC 6902) operations from the diff?
  3. What is the time and space complexity for deeply nested structures?
  4. How would you make the diff output human-readable for a UI changelog?

Full Details

Problem

Write a function that compares two JSON-like objects (nested dicts/arrays) and returns a structured diff describing what changed between old and new.

The diff should report:
- "added": keys present in new but not old.
- "removed": keys present in old but not new.
- "modified": keys present in both but with different values (recurse into nested objects).

python
def json_diff(old: dict, new: dict) -> dict:
    ...

Example:

old = {"a": 1, "b": {"x": 10, "y": 20}, "c": 3}
new = {"a": 1, "b": {"x": 99, "z": 30}, "d": 4}

json_diff(old, new) ->
{
  "added":   {"d": 4},
  "removed": {"c": 3},
  "modified": {
    "b": {
      "added":   {"z": 30},
      "removed": {"y": 20},
      "modified": {"x": {"old": 10, "new": 99}}
    }
  }
}

Follow-ups

  1. How do you handle arrays - element-wise comparison, or treat as a whole value?
  2. How would you produce a flat list of JSON Patch (RFC 6902) operations from the diff?
  3. What is the time and space complexity for deeply nested structures?
  4. How would you make the diff output human-readable for a UI changelog?

About This Question

This is a reported interview question from a gusto interview during the onsite round.

It covers the following topics: Coding, Arrays, Onsite .