Design Algorithm to Minimize Payments in Expense-Sharing App
Company: Pinterest
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates algorithm design and optimization skills, focusing on modeling multi-party transactions and minimizing the number of settlement operations.
Constraints
- 1 <= len(transactions) <= 200000
- Each transaction is [payer, payee, amount] with payer and payee as non-empty ASCII names (length 1..32)
- 1 <= amount <= 10^9 (integers)
- Number of distinct people P <= 200000
- Total of all amounts fits in 64-bit signed integer
- Output must follow the specified greedy rule; ties broken by lexicographically smallest names
Hints
- Compute each person's net balance: decrement payer by amount, increment payee by amount.
- Maintain two max-heaps: one for creditors (positive balance) and one for debtors (absolute value of negative balance).
- At each step, pop the largest debtor and largest creditor, transfer the smaller amount, and push back any remainder.
- Break ties on equal amounts by lexicographically smallest names to ensure deterministic output.