KatInterview

In-Memory Ledger with Timed Transfers and Account Consolidation

Data Structure DesignModel answer
HardModel answerData Structure Designheaphash-mapscheduling

Last updated

Design an in-memory financial ledger supporting deposits, transfers, scheduled future payments, top-K spending rankings, and account merges with pending-payment reconciliation.

In-Memory Ledger with Timed Transfers and Account Consolidation

You are building an in-memory financial ledger for a simulation platform. The ledger must support the six operations below. For each one, define a clear method signature, the data structures you would use, the expected time and space complexity, and any consistency or idempotency guarantees.

Operations

1. open_account(account_id) Register a new account with a zero balance. Reject if the id is already active or was previously retired by a consolidation.

2. deposit(account_id, amount) Add amount (positive integer, in cents) to the account's balance.

3. transfer(src_id, dst_id, amount) Move amount from src to dst. Return True on success, False if funds are insufficient. Reject zero or negative amounts, transfers to the same account, and transfers involving unknown or retired accounts.

4. top_spenders(k) Return the k accounts with the highest cumulative outgoing amounts (sum of all successful debits, including executed scheduled payments), ordered by outgoing total descending. Break ties by account_id ascending. If fewer than k accounts exist, return all of them.

5. schedule_transfer(src_id, dst_id, amount, execute_at_ms) Queue a payment to run at or after the epoch-millisecond timestamp execute_at_ms. When a payment becomes due, attempt it exactly once. If the source balance is insufficient at that moment, mark the payment skipped — do not retry. A payment scheduled in the past executes immediately during the next operation's catch-up step.

6. consolidate(primary_id, secondary_id) Merge the secondary account into the primary. The primary survives; the secondary is retired. Combine balances and outgoing totals. Any pending scheduled payments that referenced the secondary account should seamlessly apply to the primary after consolidation — without being rewritten or re-queued. If a pending payment's source and destination resolve to the same account after consolidation, cancel it.

Scheduling contract

Every operation receives a timestamp argument representing the caller's current time. Before executing the operation itself, the ledger must first process all scheduled payments whose execute_at_ms is less than or equal to timestamp, in chronological order (ties broken by scheduling sequence). This "catch-up then act" rule makes execution deterministic regardless of whether a background timer or an inline call triggers it.

What your answer should cover

  • The concrete data structures for balances, outgoing totals, the schedule, account aliasing after consolidations, and idempotent request caching.
  • How top_spenders stays consistent as transfers, scheduled payments, and consolidations mutate outgoing totals, and the trade-off between a simpler O(n log k) query approach versus maintaining a sorted structure for O(log n) updates and O(k) queries.
  • Correctness arguments: money conservation, at-most-once execution of each scheduled payment, and what happens when two payments are due at the same millisecond.
  • Complexity table for all six operations plus the catch-up step.
  • Edge cases: zero/negative amounts; self-transfer after consolidation; consolidating an account with itself; chained consolidations (c→b then b→a); ties in top_spenders; k larger than the account count; a payment whose execute_at_ms is already in the past when scheduled.
  • A working implementation in Python (or a language of your choice) that demonstrates the core logic.

Hints

Hint 1

For scheduled payments, a min-heap keyed by (execute_at_ms, sequence_number) gives O(log P) insertion and lets you pop due payments in order during each catch-up step. The sequence number breaks ties and preserves scheduling order when two payments share the same timestamp.

Hint 2

You don't need to rewrite every pending payment when two accounts consolidate. Instead, store a lazy alias map from retired ids to their surviving replacement. Resolve source and destination through this map at execution time. Path-compress the chain so that repeated consolidations (c→b→a) stay near-O(1) per lookup.

Hint 3

For top_spenders, start with a plain hash map of outgoing totals and use heapq.nsmallest(k, …) at query time — O(n log k), simple to implement. If the interview pushes on query frequency, describe the upgrade path: maintain a SortedList of (-total_out, account_id), making each update O(log n) and each query O(k). State the trade-off explicitly rather than over-engineering up front.