KatInterview

Clean and Reconcile Account Snapshots from a JSON Feed

Arrays & HashingModel answer
EasyModel answerArrays & Hashingpythonjsondecimal

Last 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 account
  • balance: a JSON number
  • updated_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:

  1. Validate. Discard a record if any field is missing, if the balance is not a finite number (for example NaN or Infinity), or if it is otherwise unusable (see the rules below).
  2. Deduplicate. For each account_id, keep only the valid record with the latest updated_at.
  3. Aggregate. Return a dictionary with:
    • total_balance: the sum of the balances of the surviving records, as a float rounded to two decimal places
    • account_map: a mapping from account_id to 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.