Validate and Deduplicate JSON Account Balances

Easy · Data Manipulation (SQL/Python) · Machine Learning Engineer · Onsite

Problem Statement

Write a function process_accounts(json_data: str) -> dict that ingests a JSON array of raw bank account snapshots, discards malformed entries, selects each account's latest valid snapshot, and computes an exact portfolio summary.

Every valid element in the top-level JSON array is a JSON object containing three keys:

  • account_id: a non-empty string identifying the account.
  • balance: a finite JSON numeric literal (integers, zero, and negative overdraft amounts are valid; strings such as "12.50" or "pending", booleans, null, arrays, objects, NaN, Infinity, and -Infinity are invalid). Parse numeric tokens directly as Decimal values so every digit in the JSON text is retained without binary floating-point distortion.
  • updated_at: an ISO 8601 date-time string supported by datetime.fromisoformat. Compare timestamps by their true chronological instant; if a timestamp omits a timezone offset, treat it as UTC (+00:00).

Your implementation must execute three stages:

  1. Sanitize first: Drop any array element that is not a JSON object, lacks any required key, or fails the account_id, balance, or updated_at rules above. If the top-level JSON value is not an array, raise ValueError.
  2. Keep newest per account: Across valid snapshots sharing the same account_id, retain the snapshot with the latest updated_at instant. Because malformed entries are discarded first, a newer corrupted entry must never overwrite an earlier valid snapshot. When two valid snapshots for the same account share the exact same instant, keep whichever appears later in the array.
  3. Summarize: Return a dictionary with two entries:
    • "account_map": a dict mapping each surviving account_id to its exact Decimal balance.
    • "total_balance": a float produced by summing all Decimal values in account_map, rounding that exact sum once to two decimal places via half-up rounding (ROUND_HALF_UP), and converting to float (0.0 when no valid accounts exist, normalizing -0.0 to 0.0).

Examples

Example 1

json_data = """
[
  {"account_id": "chk_10", "balance": 240.15, "updated_at": "2025-04-10T08:00:00Z"},
  {"account_id": "chk_10", "balance": 310.40, "updated_at": "2025-04-11T09:30:00Z"},
  {"account_id": "sav_22", "balance": -15.05, "updated_at": "2025-04-11T12:00:00Z"},
  {"account_id": "sav_22", "balance": "pending", "updated_at": "2025-04-12T00:00:00Z"}
]
"""
process_accounts(json_data)
# {
#   "total_balance": 295.35,
#   "account_map": {"chk_10": Decimal("310.40"), "sav_22": Decimal("-15.05")}
# }

Explanation: Account "chk_10" has two valid snapshots; the April 11 entry (310.40) is newer than the April 10 entry (240.15). For "sav_22", the April 12 row has a string balance ("pending") and is rejected during validation, preserving the valid April 11 overdraft (-15.05). The exact sum Decimal("310.40") + Decimal("-15.05") = Decimal("295.35") converts to 295.35.

Example 2

json_data = """
[
  {"account_id": "wal_7", "balance": 10.005, "updated_at": "2025-06-01T14:00:00+04:00"},
  {"account_id": "wal_7", "balance": 20.005, "updated_at": "2025-06-01T11:00:00Z"},
  {"account_id": "wal_8", "balance": 0.010, "updated_at": "2025-06-01T11:00:00Z"},
  {"account_id": "wal_9", "balance": NaN, "updated_at": "2025-06-01T11:00:00Z"}
]
"""
process_accounts(json_data)
# {
#   "total_balance": 20.02,
#   "account_map": {"wal_7": Decimal("20.005"), "wal_8": Decimal("0.010")}
# }

Explanation: For "wal_7", 14:00:00+04:00 corresponds to 10:00:00 UTC, which is one hour earlier than 11:00:00Z, so Decimal("20.005") wins. "wal_9" is dropped because NaN is non-finite. Summing Decimal("20.005") + Decimal("0.010") = Decimal("20.015") and rounding half-up to two decimal places yields 20.02.

Constraints

  • json_data is valid JSON text (including Python json constants NaN, Infinity, -Infinity) containing up to 10^4 array elements.
  • Individual balances may carry more than 15 significant digits or sub-cent fractions; account_map must preserve exact Decimal digits without intermediate float conversion.
  • Time complexity should be linear O(L + R) in the JSON string length L and record count R.

Step-by-step walkthrough

  1. Clarify the rules for dirty financial JSON

    We receive a JSON string containing a list of bank account snapshots and must return {"total_balance": float, "account_map": {account_id: balance}} using only the most recent valid snapshot of each account.

    Real-world financial feeds contain messy edge cases, so we pin down the exact contract upfront: - Valid balance: Must be a finite JSON number (310.40, -15.05, 0). Strings ("pending", "12.50"), booleans (true), null, lists, objects, NaN, and Infinity are rejected. - Valid account_id: Must be a non-empty string. - Valid updated_at: Must be a valid ISO 8601 timestamp string; if it has no timezone offset, treat it as UTC. - Validate before deduplicating: Skip invalid records before comparing timestamps so a corrupted newer row never overwrites an older valid balance. - Ties: If two valid records for the same account have the exact same timestamp instant, keep the one that appears later in the list. - Exact arithmetic: Store exact Decimal values in account_map, sum them as Decimals, and round once at the very end to two decimal places (float).

  2. Parse JSON numbers directly into Decimal

    Standard binary floats use base-2 fractions, which cannot represent most decimal cents exactly (floating-point representation error): for instance, 0.1 is stored as 0.10000000000000000555..., and a 19-digit balance like 1234567890.123456789 permanently loses its trailing digits the moment json.loads creates a float. Calling Decimal(x) after json.loads is too late because the digits are already gone.

    Instead, Python's json.loads accepts three hooks that intercept raw number tokens while they are still strings: - parse_float=Decimal and parse_int=Decimal build every JSON number directly from its exact characters. - parse_constant=Decimal turns Python's non-standard JSON tokens (NaN, Infinity, -Infinity) into Decimal objects, which value.is_finite() cleanly rejects.

    This gives us a bonus safety win: booleans (true/false), strings, null, lists, and dicts are never passed to those hooks, so checking isinstance(value, Decimal) automatically rejects "12.50" and true (avoiding the classic Python trap where isinstance(True, int) is True!).

    def _parse_balance(value: Any) -> Optional[Decimal]:
        """Return value as a finite Decimal, or None if it was not a finite JSON number."""
        if not isinstance(value, Decimal):
            return None
        if not value.is_finite():
            return None
        return value
    
  3. Parse ISO 8601 timestamps as real instants

    ISO 8601 is the international standard format for writing dates and times as strings, such as "2025-06-01T11:00:00Z" (Z means UTC, offset +00:00) or "2025-06-01T14:00:00+04:00" (four hours ahead of UTC).

    Never compare timestamp strings alphabetically unless every single producer uses the exact same timezone and precision:

    String comparison (WRONG):
      "2025-06-01T14:00:00+04:00"  >  "2025-06-01T11:00:00Z"   ('4' > '1' at hour digit)
    
    Actual UTC timeline (RIGHT):
      14:00+04:00 == 10:00 UTC    <   11:00 UTC                (14:00+04:00 is 1 hour EARLIER!)
    

    datetime.fromisoformat(value) parses the text into a datetime object that compares timezone-aware timestamps by their true UTC instant. If a timestamp omits its timezone offset (moment.tzinfo is None), Python calls it "naive" and raises TypeError if compared against an offset-aware timestamp—so we attach timezone.utc to naive timestamps right away.

    def _parse_timestamp(value: Any) -> Optional[datetime]:
        """Parse an ISO 8601 string into a timezone-aware datetime, or None if invalid."""
        if not isinstance(value, str):
            return None
        try:
            moment = datetime.fromisoformat(value)
        except ValueError:
            return None
        if moment.tzinfo is None:
            moment = moment.replace(tzinfo=timezone.utc)
        return moment
    
  4. Validate one record cleanly

    Putting all record-level checks inside one helper _parse_record(record) keeps the main pipeline easy to read. Either a record satisfies every check and returns (account_id, balance, updated_at), or it returns None and is ignored. Notice that a field set to null in JSON becomes None in Python, which fails isinstance(..., str) or isinstance(..., Decimal) and is rejected just like a missing key.

    REQUIRED_FIELDS = ("account_id", "balance", "updated_at")
    
    
    def _parse_record(record: Any) -> Optional[Tuple[str, Decimal, datetime]]:
        """Validate one raw JSON element and return (account_id, balance, updated_at) or None."""
        if not isinstance(record, dict):
            return None
        for field in REQUIRED_FIELDS:
            if field not in record:
                return None
    
        account_id = record["account_id"]
        if not isinstance(account_id, str) or account_id == "":
            return None
    
        balance = _parse_balance(record["balance"])
        updated_at = _parse_timestamp(record["updated_at"])
        if balance is None or updated_at is None:
            return None
        return account_id, balance, updated_at
    
  5. Deduplicate in one pass with a dictionary

    Instead of sorting all R records in O(R log R) time, we scan the list once and maintain a dictionary latest_by_account mapping each account_id to (latest_updated_at, validated_balance).

    Whenever a valid record arrives, we store it if the account has not been seen yet or if updated_at >= latest_by_account[account_id][0]: - Because invalid records were already skipped by if parsed is None: continue, a newer NaN record can never overwrite an older valid balance. - Using >= instead of > means that if two records share the exact same timestamp, the later one in the input list wins.

    latest_by_account: Dict[str, Tuple[datetime, Decimal]] = {}
    for record in records:
        parsed = _parse_record(record)
        if parsed is None:
            continue
        account_id, balance, updated_at = parsed
        if account_id not in latest_by_account or updated_at >= latest_by_account[account_id][0]:
            latest_by_account[account_id] = (updated_at, balance)
    
  6. Sum exact Decimals and round once at the end

    Suppose Account A holds 0.005 and Account B holds 0.010. Their true sum is 0.015, which rounds to 0.02 cents. In binary float, 0.005 + 0.010 evaluates to 0.01499999999999999944...—just under half a cent—so round(0.005 + 0.010, 2) wrongly returns 0.01!

    Summing Decimal values keeps every digit exact, and .quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) rounds once at the end using standard half-up financial rounding (0.015 -> 0.02). Finally, if a tiny negative balance like -0.001 rounds to Decimal("-0.00"), float(...) produces IEEE-754 -0.0, so if total_balance == 0.0: total_balance = 0.0 normalizes it cleanly to 0.0.

    CENT = Decimal("0.01")
    
    account_map: Dict[str, Decimal] = {}
    exact_total = Decimal("0")
    for account_id, (updated_at, balance) in latest_by_account.items():
        account_map[account_id] = balance
        exact_total += balance
    
    rounded_total = exact_total.quantize(CENT, rounding=ROUND_HALF_UP)
    total_balance = float(rounded_total)
    if total_balance == 0.0:
        total_balance = 0.0
    
  7. Trace Example 1 record by record

    Let's trace the four records from Example 1:

    Row  Raw JSON fields                                 _parse_record result                 latest_by_account after row
    ---  ----------------------------------------------  -----------------------------------  ---------------------------------------------------
     0   chk_10, 240.15,    "2025-04-10T08:00:00Z"       ("chk_10", Decimal("240.15"), Apr10) {"chk_10": (Apr10, 240.15)}
     1   chk_10, 310.40,    "2025-04-11T09:30:00Z"       ("chk_10", Decimal("310.40"), Apr11) {"chk_10": (Apr11, 310.40)}  <- Apr11 >= Apr10
     2   sav_22, -15.05,    "2025-04-11T12:00:00Z"       ("sav_22", Decimal("-15.05"), Apr11) {"chk_10": (Apr11, 310.40), "sav_22": (Apr11, -15.05)}
     3   sav_22, "pending", "2025-04-12T00:00:00Z"       None (str is not Decimal)            unchanged (corrupted newer row skipped!)
    
    Aggregation:
      account_map   = {"chk_10": Decimal("310.40"), "sav_22": Decimal("-15.05")}
      exact_total   = Decimal("310.40") + Decimal("-15.05") = Decimal("295.35")
      total_balance = float(Decimal("295.35")) = 295.35
    
  8. Complete solution

    from typing import Any, Dict, Optional, Tuple
    import json
    from datetime import datetime, timezone
    from decimal import Decimal, ROUND_HALF_UP
    
    REQUIRED_FIELDS = ("account_id", "balance", "updated_at")
    CENT = Decimal("0.01")
    
    
    def _parse_balance(value: Any) -> Optional[Decimal]:
        """Return value as a finite Decimal, or None if it was not a finite JSON number."""
        # Because json.loads below uses parse_float=Decimal, parse_int=Decimal, and
        # parse_constant=Decimal, ONLY JSON numeric tokens (and NaN/Infinity) become Decimal.
        # Strings, booleans (even though bool subclasses int!), null, lists, and dicts do not.
        if not isinstance(value, Decimal):
            return None
        if not value.is_finite():
            return None
        return value
    
    
    def _parse_timestamp(value: Any) -> Optional[datetime]:
        """Parse an ISO 8601 string into a timezone-aware datetime, or None if invalid."""
        if not isinstance(value, str):
            return None
        try:
            moment = datetime.fromisoformat(value)
        except ValueError:
            return None
        # Treat timestamps without an explicit offset as UTC so all datetimes can be compared.
        if moment.tzinfo is None:
            moment = moment.replace(tzinfo=timezone.utc)
        return moment
    
    
    def _parse_record(record: Any) -> Optional[Tuple[str, Decimal, datetime]]:
        """Validate one raw JSON element and return (account_id, balance, updated_at) or None."""
        if not isinstance(record, dict):
            return None
        for field in REQUIRED_FIELDS:
            if field not in record:
                return None
    
        account_id = record["account_id"]
        if not isinstance(account_id, str) or account_id == "":
            return None
    
        balance = _parse_balance(record["balance"])
        updated_at = _parse_timestamp(record["updated_at"])
        if balance is None or updated_at is None:
            return None
        return account_id, balance, updated_at
    
    
    def process_accounts(json_data: str) -> dict:
        """Validate, deduplicate (latest updated_at wins), and aggregate account balances."""
        # Phase 1: Parse JSON text, building Decimals directly from raw digit strings
        # so binary float rounding never touches any balance.
        records = json.loads(
            json_data,
            parse_float=Decimal,
            parse_int=Decimal,
            parse_constant=Decimal,
        )
        if not isinstance(records, list):
            raise ValueError("expected a JSON list of account records")
    
        # Phase 2: Validate first, then deduplicate in one pass.
        # latest_by_account: maps account_id -> (latest_updated_at, validated_balance)
        latest_by_account: Dict[str, Tuple[datetime, Decimal]] = {}
        for record in records:
            parsed = _parse_record(record)
            if parsed is None:
                continue
            account_id, balance, updated_at = parsed
            # Use '>=' so that on an exact timestamp tie, the later record in the input wins.
            if account_id not in latest_by_account or updated_at >= latest_by_account[account_id][0]:
                latest_by_account[account_id] = (updated_at, balance)
    
        # Phase 3: Build account_map and sum exact Decimal balances before rounding once.
        account_map: Dict[str, Decimal] = {}
        exact_total = Decimal("0")
        for account_id, (updated_at, balance) in latest_by_account.items():
            account_map[account_id] = balance
            exact_total += balance
    
        rounded_total = exact_total.quantize(CENT, rounding=ROUND_HALF_UP)
        total_balance = float(rounded_total)
        # Normalize IEEE-754 negative zero (-0.0 from e.g. Decimal('-0.001')) to +0.0.
        if total_balance == 0.0:
            total_balance = 0.0
    
        return {"total_balance": total_balance, "account_map": account_map}
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture reconciling a shoebox of paper bank slips where each slip lists an account ID, a dollar balance, and a clock timestamp. You inspect one slip at a time: if any field is missing, unreadable, or nonsensical (like "pending" or NaN), you toss that slip straight into the recycle bin; otherwise, you check the folder for that account ID and swap the slip inside only if the new slip's clock time is at least as recent. Once every slip has been checked, you add up all folders on an exact decimal calculator (Decimal, a base-10 number type that stores exact decimal digits instead of binary approximations) and round the grand total once at the very end.

Three naive shortcuts fail subtly on financial data: 1. Calling plain json.loads parses numbers into binary floats, introducing floating-point representation error (base-2 rounding noise where 20.005 + 0.010 or 0.005 + 0.010 can drift just below a half-cent boundary and round down instead of up, and 19-digit numbers lose trailing digits immediately). 2. Comparing ISO 8601 timestamp strings (standard date-time text like "2025-06-01T14:00:00+04:00") alphabetically gets different timezones backwards ("14:00+04:00" is 10:00 UTC, an hour earlier than "11:00Z", yet sorts later as text). 3. Deduplicating before validating lets a newer corrupted NaN or string record erase an account's older valid balance.

Walk through Example 1's four records: 1. {"account_id": "chk_10", "balance": 240.15, "updated_at": "2025-04-10T08:00:00Z"} parses cleanly into ("chk_10", Decimal("240.15"), 2025-04-10 08:00 UTC) and becomes "chk_10"'s current entry. 2. {"account_id": "chk_10", "balance": 310.40, "updated_at": "2025-04-11T09:30:00Z"} is valid and its April 11 timestamp is newer than April 10, so "chk_10" updates to Decimal("310.40"). 3. {"account_id": "sav_22", "balance": -15.05, "updated_at": "2025-04-11T12:00:00Z"} records a valid overdraft Decimal("-15.05") for "sav_22". 4. {"account_id": "sav_22", "balance": "pending", "updated_at": "2025-04-12T00:00:00Z"} fails _parse_balance because "pending" is a str rather than a Decimal, so it is skipped—leaving account_map = {"chk_10": Decimal("310.40"), "sav_22": Decimal("-15.05")} and total_balance = 295.35.

Complexity

  • Time: O(L + R), where L is the length of json_data in characters and R is the number of records. json.loads scans the L characters once, and our loop inspects each of the R records once with O(1) dictionary lookups and fixed-length ISO timestamp parsing—avoiding an O(R log R) sort.
  • Space: O(L + A), where A is the number of distinct valid accounts (A <= R). json.loads materializes the full JSON list in O(L) memory, while latest_by_account and account_map store one entry per unique valid account in O(A) memory.

Edge cases

  • Empty JSON array ("[]"): Returns {"total_balance": 0.0, "account_map": {}}.
  • Non-finite tokens (NaN, Infinity, -Infinity): Python's json.loads accepts these non-standard tokens by default; parse_constant=Decimal turns them into Decimals that value.is_finite() cleanly filters out.
  • Booleans as balances (true / false): In Python, bool is a subclass of int (isinstance(True, int) is True), so naive numeric checks accept true as 1. Using parse_int=Decimal avoids this completely because booleans stay bool and fail isinstance(value, Decimal).
  • Newer invalid record for an existing account: Skipped during validation before touching latest_by_account, preserving the older valid balance.
  • Mixed timezone offsets and naive timestamps: Converting naive timestamps to UTC allows datetime comparison to order "10:00+05:00" (05:00 UTC), "05:30" (05:30 UTC), and "06:00Z" (06:00 UTC) without TypeError.
  • Negative balances and -0.0: Valid negative balances (overdrafts) are kept; if tiny negative balances like -0.001 round to Decimal("-0.00"), normalizing if total_balance == 0.0: total_balance = 0.0 avoids returning -0.0.
  • Astronomical exponents (e.g., 1e400): Decimal's default precision is 28 significant digits (enough for totals up to 10^26 written to the cent); if untrusted inputs can contain absurd exponents, reject abs(balance) > MAX_ALLOWED in _parse_balance so quantize never raises InvalidOperation.

Common mistakes

  • Calling Decimal(x) or Decimal(str(x)) after default json.loads: The binary float has already truncated digits beyond ~15–17 significant figures before Decimal ever sees the value.
  • Checking field presence with if not record.get("balance"):: Zero (Decimal("0") or 0.00) is falsy in Python, so valid zero-balance accounts get silently dropped! Always check "balance" in record and balance is not None.
  • Comparing updated_at as raw strings: Fails whenever timestamps mix Z, +00:00, other timezone offsets, or fractional seconds (10:00:00.500Z vs 10:00:00Z).
  • Rounding each account's balance before summing: Rounding N balances individually can accumulate up to 0.005 × N dollars of drift compared to summing exact Decimals and rounding once.
  • Deduplicating before validating: Storing raw records by latest timestamp first and filtering invalid balances afterward mistakenly deletes accounts whose newest snapshot was corrupted.

Follow-up questions

  • How would you adapt this pipeline when the input JSON payload is tens of gigabytes and exceeds available RAM? Replace json.loads (which loads the whole file at once) with a streaming parser such as ijson.items(file, "item") (which yields one array object at a time with Decimal numbers), or switch the upstream format to JSON Lines—a file format where each line is an independent JSON object—and iterate line by line. That drops memory from file size O(L) to unique-account count O(A) (1,000,000 accounts in latest_by_account use roughly 300 MB in Python). If even A exceeds single-machine RAM, hash-partition lines by hash(account_id) % K into K temporary disk shards in pass 1, then run process_accounts on each shard independently in pass 2 and sum their exact Decimal shard totals before rounding once.
  • What mechanisms guarantee atomic updates and idempotent retries if a worker crashes partway through ingesting a batch? Atomicity means an output update happens all-at-once or not-at-all, so readers never see a half-written result; achieve it by writing to a temporary file and calling os.replace(tmp_path, final_path) (an atomic POSIX rename) or committing inside a single database transaction. Idempotency means re-running the same batch after a crash produces the exact same state as running it once; achieve it in a database with a conditional upsert (INSERT ... ON CONFLICT (account_id) DO UPDATE SET ... WHERE excluded.updated_at >= accounts.updated_at) paired with recording the processed batch ID in the same transaction.
  • How should you enforce structural schema checks and quarantine bad payloads before aggregation runs? Choose upfront between fail-fast validation (aborting the entire batch on structural errors) and row-level quarantine (routing malformed rows plus error reasons to a dead-letter queue, a separate storage table/file for rejected records so engineers can inspect them). Combine structural schema checks (using Pydantic or JSON Schema with strict types and no NaN/Infinity constants) with a circuit-breaker threshold on the rejection rate—for instance, halting the pipeline if more than 1% of rows fail validation, which catches silent upstream schema changes before publishing an incomplete total.

Follow-up questions

Similar questions

More Dave interview questions

All 2 Dave questions →