Compute balances with transaction fees and rejections
Company: Stripe
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates transaction processing, ledger state management, handling of edge cases like insufficient funds and fixed fees, and efficient use of data structures and integer arithmetic.
Constraints
- 0 <= len(accounts) <= 10^5
- 0 <= len(transactions) <= 10^5
- len(accounts) == len(initial_balances)
- Account names in `accounts` are unique
- `amount > 0` and `fee > 0`
- Balances, amounts, and fees fit in 64-bit signed integers
Examples
Input: (["alice", "bob"], [100, 20], [("alice", "bob", 30), ("bob", "charlie", 40), ("alice", "bob", 70)], 5)
Expected Output: ([('alice', 65), ('bob', 5), ('charlie', 40)], [('alice', 'bob', 70)])
Explanation: The first two transfers succeed. The last one is rejected because alice has 65, but needs 75. Final non-zero balances are sorted by account name.
Input: (["a"], [10], [("ghost", "a", 1), ("a", "b", 8), ("b", "a", 6)], 2)
Expected Output: ([('a', 6)], [('ghost', 'a', 1)])
Explanation: ghost is not in the initial list, so its balance is 0 and the first transfer is rejected. The next two transfers succeed, and account b ends at 0 so it is omitted from the final balances.
Input: ([], [], [], 3)
Expected Output: ([], [])
Explanation: With no accounts and no transactions, there are no balances to report and no rejections.
Input: (["x", "y"], [7, 0], [("x", "y", 5)], 2)
Expected Output: ([('y', 5)], [])
Explanation: x has exactly amount + fee = 7, so the transfer is accepted. x ends at 0 and is omitted.
Input: (["self"], [10], [("self", "self", 7)], 3)
Expected Output: ([('self', 7)], [])
Explanation: A transfer to the same account is allowed. The net effect is only the fee being lost, so self goes from 10 to 7.
Hints
- Use a hash map from account name to current balance so each transaction can be checked and updated in O(1) average time.
- Process transactions strictly in order, and only sort the remaining non-zero balances once at the end.