The Change Tracker

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L3
Asked in
Circana

Problem

Report the ids that were added, removed, and modified between old_records and new_records, two snapshots of the same user table an analyst is reconciling, with each list of ids in ascending order. Records correspond by id wherever they sit in either list, and a record present in both counts as modified when any of its other fields differs.

Before and after snapshots. The delta is in there.

Example

Input:

old_records = [{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}], new_records = [{"id":1,"name":"Alice"},{"id":2,"name":"Robert"},{"id":3,"name":"Carol"}]

Output:

{"added":[3],"removed":[],"modified":[2]}

Worked solution and explanation

Why this problem exists in real interviews

Detecting added, removed, and modified records between two snapshots is SCD (Slowly Changing Dimension) Type 2 logic in Python form. It tests set operations and record comparison.


Break down the requirements

Step 1: Index both record lists by 'id'

Build dicts keyed by the id field for O(1) lookup.

Step 2: Compute added, removed, and modified sets

Added: ids in new but not old. Removed: ids in old but not new. Modified: ids in both where any non-id field differs.

Step 3: Return sorted id lists

Each result list should be sorted for deterministic output.


The solution

Set-based change detection with sorted output
def detect_changes(old_records, new_records):
    old_by_id = {}
    for r in old_records:
        old_by_id[r['id']] = r
    new_by_id = {}
    for r in new_records:
        new_by_id[r['id']] = r
    old_ids = set(old_by_id.keys())
    new_ids = set(new_by_id.keys())
    added = sorted(new_ids - old_ids)
    removed = sorted(old_ids - new_ids)
    modified = []
    for rid in sorted(old_ids & new_ids):
        if old_by_id[rid] != new_by_id[rid]:
            modified.append(rid)
    result = {
        'added': added,
        'removed': removed,
        'modified': modified
    }
    return result

Common follow-up questions