Implement a banking operations system
Company: Instacart
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of data structures, state management, transactional correctness and edge-case handling (including invalid or negative amounts and overdraft prevention) when implementing deposit, withdraw, and transfer operations.
Constraints
- 0 <= number of accounts <= 10^5
- 0 <= number of operations <= 10^5
- Initial balances are non-negative integers.
- amount may be any integer; only strictly positive amounts can produce a successful operation.
- Account ids are unique strings.
- A rejected operation must leave all balances unchanged.
Examples
Input: ({'A': 100, 'B': 50}, [['deposit', 'A', 50], ['withdraw', 'B', 20], ['transfer', 'A', 'B', 100]])
Expected Output: [[True, True, True], {'A': 50, 'B': 130}]
Explanation: Deposit 50 into A (100->150 then transfer takes 100), withdraw 20 from B (50->30), transfer 100 from A to B succeeds since A has 150. Final: A=50, B=130.
Input: ({'A': 100}, [['withdraw', 'A', 200], ['deposit', 'A', 0], ['deposit', 'A', -10], ['transfer', 'A', 'C', 10]])
Expected Output: [[False, False, False, False], {'A': 100}]
Explanation: Overdraw (200 > 100) rejected; zero amount rejected; negative amount rejected; transfer to non-existent account C rejected. Balance of A is unchanged at 100.
Input: ({}, [['deposit', 'X', 10]])
Expected Output: [[False], {}]
Explanation: Account X does not exist in an empty bank, so the deposit is rejected and the bank stays empty.
Input: ({'A': 0, 'B': 0}, [])
Expected Output: [[], {'A': 0, 'B': 0}]
Explanation: No operations to apply; results is empty and balances are returned unchanged.
Input: ({'A': 100, 'B': 100}, [['transfer', 'A', 'A', 50], ['withdraw', 'A', 100], ['transfer', 'A', 'B', 1]])
Expected Output: [[False, True, False], {'A': 0, 'B': 100}]
Explanation: Self-transfer A->A is rejected; withdraw 100 from A drains it to 0; transfer of 1 from A now fails because A has insufficient funds. Final: A=0, B=100.
Hints
- Use a hash map (dict) keyed by account id for O(1) existence checks and balance updates.
- Validate every precondition BEFORE mutating any balance, so a rejected operation leaves state untouched. For a transfer, check both accounts exist, the amount is positive, source != destination, and the source can cover the amount before moving any funds.
- Treat zero and negative amounts as invalid for every operation type. For a stream, process each operation in O(1) as it arrives — no need to buffer; the same per-operation validation logic applies online.