Design and implement an in-memory banking system that supports:
(
-
CreateAccount(id, initialBalance) and Transfer(fromId, toId, amount) with validation for nonnegative amounts, sufficient funds, account existence, idempotency via transaction IDs, and atomic balance updates;
(
-
a query to return the accounts with the top k total outgoing funds across all transfers, specifying output format, tie-breaking, and expected time/space complexity (e.g., maintain running aggregates for O(log n) updates and O(k log n) queries);
(
-
a Purchase(accountId, amount, txnId) that awards 2% cashback credited exactly 24 hours after the purchase, requiring a structure for pending rewards, a scheduler or sweep to post credits, and idempotent, crash-safe processing;
(
-
MergeAccount(primaryId, duplicateId) to combine balances and transaction histories, redirect future operations from duplicateId to primaryId, and reconcile pending cashback and duplicate transaction IDs. Discuss chosen data structures, concurrency assumptions (single-threaded vs. multi-threaded), and provide unit tests for edge cases (insufficient funds, duplicate transfers, simultaneous merges, and time-bound rewards).