PythonStudio
Interview Problems

Expense Sharing (Splitwise)

medium · balances, greedy settlement

Brief-reported interview attribution (unverified): Flipkart, Amazon, Uber

How to approach an LLD round

Design the core of Splitwise. Friends record expenses; each expense is split equally among its participants (the payer is a participant like anyone else). Balances are integer cents: positive means others owe this person. settle_up returns the deterministic greedy transactions that settle everyone, as (debtor, creditor, amount_cents) tuples sorted by (debtor, creditor).

class Splitwise:
    def __init__(self):
    def add_expense(self, payer, amount_cents, participants):
        # -> True if recorded, False if the participant list is empty or the amount is negative
    def balance(self, person):
        # -> net balance in cents (0 for an unknown person)
    def all_balances(self):
        # -> {person: balance} for everyone with a non-zero balance, sorted by person
    def settle_up(self):
        # -> [(debtor, creditor, amount_cents), ...] sorted by (debtor, creditor)

Rules. An equal split divides the amount into amount // n per participant; the amount % n leftover cents go one each to the first participants in the list order. The payer's balance increases by the full amount they paid; every participant's balance decreases by their share. Settlement is greedy: repeatedly match the largest debtor with the largest creditor (ties broken by name), settling the smaller of the two amounts. People with a zero balance never appear in settle_up.

The specified greedy settlement is not a guarantee of the globally fewest transactions.

Money units: all amounts and balances are integer cents.

Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.

Public demo

# Public demo: run after implementing the class API above.
s = Splitwise()
s.add_expense('Alice', 1000, ['Alice', 'Bob'])
print(s.balance('Alice'))
print(s.balance('Bob'))
print(s.settle_up())

Starter code

class Splitwise:

    def __init__(self):
        """Initialize the state described in the problem."""
        pass

    def add_expense(self, payer, amount_cents, participants):
        """-> True if recorded, False if the participant list is empty or the amount is negative"""
        pass

    def balance(self, person):
        """-> net balance in cents (0 for an unknown person)"""
        pass

    def all_balances(self):
        """-> {person: balance} for everyone with a non-zero balance, sorted by person"""
        pass

    def settle_up(self):
        """-> [(debtor, creditor, amount_cents), ...] sorted by (debtor, creditor)"""
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler