Position: SR. Software Engineer
A one-hour phone screen, and the question was a variant of LC 465 — it felt like it needed the accounting concept of settling balances, and if you hadn't seen something like this before you probably couldn't have gotten it.
The problem was roughly this: a group of friends goes on a trip, and you're given a list of transactions. Each one has a payer, an amount, and payees — that is, who paid, how much, and who it was paid on behalf of. We need to output how much each person should pay to whom so that everyone's accounts are settled. Order doesn't matter.
My approach: at first I thought about who pays back whom directly, which turns into a complicated graph, but actually you just need to:
Build one overall ledger (a hashmap) — when someone pays, add the amount to their balance; when someone owes, subtract amount/number_of_people from their balance. That tells you how much each person finally needs to receive or pay.
Then build two lists of "assets" — creditors and debtors. Loop through the ledger: people who are owed money go into creditors, people who owe money go into debtors.
Finally, settle it greedily: take all of debtors[-1]'s money and pay it to creditors[-1]. If that's not enough, pop the last debtor and move on to the next one. By the end, once you've looped through both lists, both sides should land at 0.
The payments made along the way are the output we need — record them as you go.
The output looks like this:
transactions = [
{ 'payer': 'Alice', 'amount': 4000, 'payees': ['Bob', 'Alice', 'Charlie', 'Daisy'] },
{ 'payer': 'Charlie', 'amount': 2000, 'payees': ['Alice', 'Charlie'] }
]
Feel free to ask if you have questions.
Discussion
Loading comments…