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-Infinityare invalid). Parse numeric tokens directly asDecimalvalues so every digit in the JSON text is retained without binary floating-point distortion.updated_at: an ISO 8601 date-time string supported bydatetime.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:
- Sanitize first: Drop any array element that is not a JSON object, lacks any required key, or fails the
account_id,balance, orupdated_atrules above. If the top-level JSON value is not an array, raiseValueError. - Keep newest per account: Across valid snapshots sharing the same
account_id, retain the snapshot with the latestupdated_atinstant. 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. - Summarize: Return a dictionary with two entries:
"account_map": adictmapping each survivingaccount_idto its exactDecimalbalance."total_balance": afloatproduced by summing allDecimalvalues inaccount_map, rounding that exact sum once to two decimal places via half-up rounding (ROUND_HALF_UP), and converting tofloat(0.0when no valid accounts exist, normalizing-0.0to0.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_datais valid JSON text (including PythonjsonconstantsNaN,Infinity,-Infinity) containing up to10^4array elements.- Individual balances may carry more than 15 significant digits or sub-cent fractions;
account_mapmust preserve exactDecimaldigits without intermediatefloatconversion. - Time complexity should be linear
O(L + R)in the JSON string lengthLand record countR.
Step-by-step walkthrough
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, andInfinityare rejected. - Validaccount_id: Must be a non-empty string. - Validupdated_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 exactDecimalvalues inaccount_map, sum them asDecimals, and round once at the very end to two decimal places (float).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.1is stored as0.10000000000000000555..., and a 19-digit balance like1234567890.123456789permanently loses its trailing digits the momentjson.loadscreates afloat. CallingDecimal(x)afterjson.loadsis too late because the digits are already gone.Instead, Python's
json.loadsaccepts three hooks that intercept raw number tokens while they are still strings: -parse_float=Decimalandparse_int=Decimalbuild every JSON number directly from its exact characters. -parse_constant=Decimalturns Python's non-standard JSON tokens (NaN,Infinity,-Infinity) intoDecimalobjects, whichvalue.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 checkingisinstance(value, Decimal)automatically rejects"12.50"andtrue(avoiding the classic Python trap whereisinstance(True, int)isTrue!).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 valueParse 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"(Zmeans 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 adatetimeobject 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 raisesTypeErrorif compared against an offset-aware timestamp—so we attachtimezone.utcto 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 momentValidate 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 returnsNoneand is ignored. Notice that a field set tonullin JSON becomesNonein Python, which failsisinstance(..., str)orisinstance(..., 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_atDeduplicate in one pass with a dictionary
Instead of sorting all
Rrecords in O(R log R) time, we scan the list once and maintain a dictionarylatest_by_accountmapping eachaccount_idto(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 byif parsed is None: continue, a newerNaNrecord 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)Sum exact Decimals and round once at the end
Suppose Account A holds
0.005and Account B holds0.010. Their true sum is0.015, which rounds to0.02cents. In binaryfloat,0.005 + 0.010evaluates to0.01499999999999999944...—just under half a cent—soround(0.005 + 0.010, 2)wrongly returns0.01!Summing
Decimalvalues 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.001rounds toDecimal("-0.00"),float(...)produces IEEE-754-0.0, soif total_balance == 0.0: total_balance = 0.0normalizes it cleanly to0.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.0Trace 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.35Complete 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
Lis the length ofjson_datain characters andRis the number of records.json.loadsscans theLcharacters once, and our loop inspects each of theRrecords once with O(1) dictionary lookups and fixed-length ISO timestamp parsing—avoiding an O(R log R) sort. - Space: O(L + A), where
Ais the number of distinct valid accounts (A <= R).json.loadsmaterializes the full JSON list in O(L) memory, whilelatest_by_accountandaccount_mapstore 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'sjson.loadsaccepts these non-standard tokens by default;parse_constant=Decimalturns them intoDecimals thatvalue.is_finite()cleanly filters out. - Booleans as balances (
true/false): In Python,boolis a subclass ofint(isinstance(True, int)isTrue), so naive numeric checks accepttrueas1. Usingparse_int=Decimalavoids this completely because booleans staybooland failisinstance(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
datetimecomparison to order"10:00+05:00"(05:00 UTC),"05:30"(05:30 UTC), and"06:00Z"(06:00 UTC) withoutTypeError. - Negative balances and
-0.0: Valid negative balances (overdrafts) are kept; if tiny negative balances like-0.001round toDecimal("-0.00"), normalizingif total_balance == 0.0: total_balance = 0.0avoids 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, rejectabs(balance) > MAX_ALLOWEDin_parse_balancesoquantizenever raisesInvalidOperation.
Common mistakes
- Calling
Decimal(x)orDecimal(str(x))after defaultjson.loads: The binaryfloathas already truncated digits beyond ~15–17 significant figures beforeDecimalever sees the value. - Checking field presence with
if not record.get("balance"):: Zero (Decimal("0")or0.00) is falsy in Python, so valid zero-balance accounts get silently dropped! Always check"balance" in recordandbalance is not None. - Comparing
updated_atas raw strings: Fails whenever timestamps mixZ,+00:00, other timezone offsets, or fractional seconds (10:00:00.500Zvs10:00:00Z). - Rounding each account's balance before summing: Rounding
Nbalances individually can accumulate up to0.005 × Ndollars of drift compared to summing exactDecimals 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 asijson.items(file, "item")(which yields one array object at a time withDecimalnumbers), 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 inlatest_by_accountuse roughly 300 MB in Python). If evenAexceeds single-machine RAM, hash-partition lines byhash(account_id) % KintoKtemporary disk shards in pass 1, then runprocess_accountson each shard independently in pass 2 and sum their exactDecimalshard 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/Infinityconstants) 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
- How would you adapt this pipeline when the input JSON payload is tens of gigabytes and exceeds available RAM?
- What mechanisms guarantee atomic updates and idempotent retries if a worker crashes partway through ingesting a batch?
- How should you enforce structural schema checks and quarantine bad payloads before aggregation runs?
Similar questions
- Diagnosing and Resolving a High-Impact Production Defect
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression