Clean and Reconcile Account Snapshots from a JSON Feed
Arrays & HashingModel answerLast updated
Parse a JSON list of account records with exact decimal arithmetic, drop invalid rows, keep the newest record per account, and report a rounded total plus a per-account map.
Reconcile an Account Snapshot
A upstream system emits a JSON string describing a batch of account records. Each record is expected to be an object with:
account_id: a string identifying the accountbalance: a JSON numberupdated_at: an ISO 8601 timestamp string
The same account can appear more than once in the batch.
Write process_accounts(json_data: str) -> dict that does the following:
- Validate. Discard a record if any field is missing, if the balance is not a finite number (for example
NaNorInfinity), or if it is otherwise unusable (see the rules below). - Deduplicate. For each
account_id, keep only the valid record with the latestupdated_at. - Aggregate. Return a dictionary with:
total_balance: the sum of the balances of the surviving records, as a float rounded to two decimal placesaccount_map: a mapping fromaccount_idto its surviving balance
Rules and constraints
- The input can contain thousands of records.
- Balances must be handled as
Decimal, not as binary floats, so that no floating-point error creeps into the sum. - A balance given as a string (e.g.
"invalid") is not a number and must be rejected. - Validation happens before deduplication: an invalid newer record must not displace a valid older one.
- Compare timestamps as actual points in time, not as raw strings.
- If the top-level JSON is malformed or is not a list, signal an error.
Example
input_json = """
[
{"account_id": "A1", "balance": 100.50, "updated_at": "2023-01-01T10:00:00Z"},
{"account_id": "A1", "balance": 150.25, "updated_at": "2023-01-02T10:00:00Z"},
{"account_id": "A2", "balance": "invalid", "updated_at": "2023-01-02T10:00:00Z"}
]
"""
# Result: {"total_balance": 150.25, "account_map": {"A1": 150.25}}
In your answer, explain your approach, state the decisions you make for ambiguous inputs, give the complexity, and provide the code.
Hints
Hint 1
Where should the conversion to Decimal happen? Look at the extra arguments `json.loads` accepts for numbers and for the non-standard constants NaN and Infinity.
Hint 2
Write one validator that returns either a clean (id, timestamp, balance) tuple or nothing. Reject booleans explicitly, since `True` is an `int` in Python, and make sure the check is done before any deduplication.
Hint 3
Keep a dict from account_id to (timestamp, balance) and replace an entry only when the new timestamp is strictly greater. Parse timestamps into timezone-aware datetimes so that offsets and a trailing `Z` compare correctly. Round once at the end with an explicit rounding mode.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a single pass of "parse, validate, keep the latest per key", followed by one aggregation step. The main risks are precision loss, sloppy validation and timestamp comparison, so I would state my contract decisions up front.
Contract decisions
- Numbers are parsed straight into
Decimal. Usingjson.loads(..., parse_float=Decimal, parse_int=Decimal, parse_constant=Decimal)means a value like100.1never passes through a binary float. Converting a float afterwards is too late:Decimal(100.1)is100.0999999999999943.... NaNandInfinityare caught. Python'sjsonaccepts these non-standard literals by default. Withparse_constant=Decimalthey become non-finite Decimals, whichis_finite()then rejects.- Balance must be a real JSON number. Because only JSON numbers become
Decimal, strings (even"100.50"),nulland booleans fail anisinstance(balance, Decimal)check. This avoids the classic bug whereTruepasses as anint. - Timestamps become aware UTC datetimes. A trailing
Zis rewritten to+00:00(fromisoformatonly acceptsZfrom Python 3.11). Naive timestamps are assumed to be UTC so that naive and aware values can be compared without aTypeError. Comparing strings would be wrong when offsets differ:2023-01-02T01:00:00+02:00is earlier than2023-01-02T00:00:00Z. - Ties keep the first record seen. A later record replaces the stored one only if its timestamp is strictly greater.
- Validate, then deduplicate. If A1's newest row has a
NaNbalance, A1 keeps its most recent valid row. - Malformed input fails loudly. Invalid JSON or a non-list top level raises
ValueError. Silently returning0.0for a corrupt batch hides real problems. - Negative balances are valid (overdrafts).
Why it is correct
After processing records 1..i, latest[id] holds the valid record for id with the maximum timestamp seen so far, with ties going to the earliest. Replacing only on a strictly greater timestamp preserves that invariant, so after the last record each id maps to its newest valid record. The total is summed in Decimal over exactly the values in account_map, and rounding happens once at the end, so there is no accumulated error.
Complexity
- Time: O(n). Parsing is linear, and each record needs O(1) dict work plus a constant-size timestamp parse.
- Space: O(n) for the parsed list that
json.loadsbuilds, plus O(u) for the map of u unique accounts.
Code
import json
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP, InvalidOperation
_CENTS = Decimal("0.01")
def _parse_timestamp(value):
if not isinstance(value, str) or not value:
return None
text = value[:-1] + "+00:00" if value.endswith(("Z", "z")) else value
try:
dt = datetime.fromisoformat(text)
except ValueError:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def _validate(record):
if not isinstance(record, dict):
return None
account_id = record.get("account_id")
balance = record.get("balance")
if not isinstance(account_id, str) or not account_id:
return None
if not isinstance(balance, Decimal) or not balance.is_finite():
return None
ts = _parse_timestamp(record.get("updated_at"))
if ts is None:
return None
return account_id, ts, balance
def process_accounts(json_data: str) -> dict:
try:
records = json.loads(
json_data,
parse_float=Decimal,
parse_int=Decimal,
parse_constant=Decimal,
)
except (json.JSONDecodeError, InvalidOperation) as exc:
raise ValueError(f"Malformed JSON input: {exc}") from exc
if not isinstance(records, list):
raise ValueError("Expected a JSON array of account records")
latest = {}
for record in records:
parsed = _validate(record)
if parsed is None:
continue
account_id, ts, balance = parsed
current = latest.get(account_id)
if current is None or ts > current[0]:
latest[account_id] = (ts, balance)
account_map = {acc: bal for acc, (_, bal) in latest.items()}
total = sum(account_map.values(), Decimal("0"))
total_balance = float(total.quantize(_CENTS, rounding=ROUND_HALF_UP))
return {"total_balance": total_balance, "account_map": account_map}
On the example, A1's second row is newer and wins, A2's string balance is dropped, and the result is total 150.25 with account_map == {"A1": Decimal("150.25")}.
Edge cases to mention
- Empty list returns
{"total_balance": 0.0, "account_map": {}}. null,true,NaN,-Infinity, strings and a missing key forbalanceare all skipped.- Bad timestamps such as
"2023-13-45",""or non-strings are skipped. - Very large integer balances stay exact thanks to
parse_int=Decimal. - A total of
0.125becomes0.13withROUND_HALF_UP; Python's built-inround()uses banker's rounding and would give0.12.
Common mistakes
- Parsing to float first and converting to Decimal later.
- Letting
TrueorFalsethrough becauseboolsubclassesint. - Comparing timestamp strings lexicographically, which breaks with mixed offsets.
- Deduplicating before validating, so a bad newer row wipes out a good older one.
- Rounding each balance instead of rounding once at the end.
Follow-ups
- Very large input: stream the array with an incremental parser such as
ijson(with exact decimals) so memory is O(u) rather than O(n). - Output as JSON: convert Decimals to strings or floats at the serialization boundary, not in the core logic.
- Reporting rejects: collect a count or list of rejected records with reasons, which is valuable for monitoring upstream data quality.