Compute transfers to balance account debts
Company: Remitly
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to convert per-account net balances into a set of transfers, testing algorithmic problem solving, data-structure manipulation, and correctness under conservation invariants in transactional systems.
Constraints
- The sum of all balances is exactly 0.
- Balances are integers; positive = owed money (receive), negative = owes money (pay).
- 0 <= number of accounts <= 10^5.
- Accounts with balance 0 are ignored and need no transfer.
- Return at most n - 1 transfers for n non-zero accounts.
Examples
Input: ({'A': -5, 'B': 2, 'C': 3},)
Expected Output: [('A', 'B', 2), ('A', 'C', 3)]
Explanation: A owes 5; it pays B (2) and C (3) in id order, settling everyone.
Input: ({},)
Expected Output: []
Explanation: No accounts means no transfers.
Input: ({'X': 0},)
Expected Output: []
Explanation: A single account already at 0 needs no transfer.
Input: ({'A': -10, 'B': 10},)
Expected Output: [('A', 'B', 10)]
Explanation: The lone debtor A pays the lone creditor B the full 10.
Input: ({'A': 4, 'B': -6, 'C': 2},)
Expected Output: [('B', 'A', 4), ('B', 'C', 2)]
Explanation: Debtor B owes 6; it pays creditor A (4) then creditor C (2), matched in id order.
Input: ({'A': -3, 'B': -2, 'C': 5},)
Expected Output: [('A', 'C', 3), ('B', 'C', 2)]
Explanation: Two debtors A and B both pay the single creditor C, fully settling C's 5.
Input: ({'D': 7, 'A': -7},)
Expected Output: [('A', 'D', 7)]
Explanation: Debtor A pays creditor D the full 7; sorting puts A's transfer first regardless of input order.
Input: ({'A': -1, 'B': -1, 'C': 1, 'D': 1},)
Expected Output: [('A', 'C', 1), ('B', 'D', 1)]
Explanation: Two independent 1-unit settlements: A->C and B->D, matched smallest-id first.
Hints
- Split accounts into debtors (negative balance) and creditors (positive balance); the absolute owed amount equals the magnitude of the balance.
- Sort both groups by accountId so the matching order is deterministic and reproducible.
- Use two pointers: transfer min(debtorOwed, creditorOwed) from the current debtor to the current creditor, subtract it from both, and advance whichever side hits 0.
- Stop when either group is exhausted; because the total sums to 0, both finish together.