2Brute2Best
πŸ”₯0
P12

Design Splitwise (Equal, Exact & Percent Splits + Simplify Debt)

Medium High-frequency interview topic Pro OnlyStrategyFactory Method
⚑ 30-Second Interview Cheat SheetP12 · 45-Min Design Plan
2 Patterns Combined
1. Scope Boundaries

In a 45-minute LLD interview, the interviewer evaluates financial domain precision, strategy isolation, and debt simplification. Scope the design to: registering users, recording expenses across three split algorithms (Equal, Exact, Percent), storing all monetary balances strictly in integer paise (int64_t) to prevent floating-point drift, and computing simplified settlement transactions using a greedy min-cash-flow algorithm. Group hierarchies and multi-currency exchange can be deferred to follow-up questions.

2. Core Noun Entities
Userdata-struct
Splitdata-struct
SplitStrategyinterface
SplitFactorystateful-class
3. Hotspot β†’ Pattern
Expense splitting calculation and validation rules (Equal vs Exact vs Percent) β†’ Strategy + Factory Method (SplitStrategy and SplitFactory)
Debt settlement transactions across multiple participants β†’ Min-Cash-Flow Algorithm (Greedy matching on net balance graph)
01

Problem statement & clarifying requirements

Design Splitwise, an expense-sharing application where friends and roommates track shared bills. The system must support Equal, Exact, and Percentage splits, rigorously validate that individual shares sum to the total bill, maintain running net balances across users, and compute simplified debt settlements to minimize the number of cash transfers needed to settle all accounts.

Questions you should ask the interviewer first
β€œHow are monetary values represented to prevent fractional rounding errors?”

All internal monetary amounts are stored as 64-bit integer paise (int64_t). No floating-point types are used for account balances or ledger transactions.

β€œHow should non-divisible odd amounts be handled in Equal splits (e.g. β‚Ή1.00 split 3 ways)?”

The remainder paise (total % n) are distributed one-by-one to the first r participants so that the sum of parts strictly equals the total.

β€œWhat validation rules apply to Exact and Percentage splits?”

Exact splits must sum exactly to the bill total. Percentage splits must sum to 100.0% within a tiny epsilon (1e-4), and the final participant absorbs rounding differences.

β€œHow does debt simplification work?”

A greedy min cash-flow algorithm pairs the largest debtor with the largest creditor, transferring min(|debt|, credit) until all net balances are cleared.

02

First, sketch the design yourself

Spend 5 minutes listing the classes, who owns whom, and which interface hides the part that changes.

  1. 1.

    Strategy Pattern for split logic: Splitting algorithms (Equal, Exact, Percent) share a common goal but have distinct validation requirements and inputs. Isolating them behind SplitStrategy preserves the Open-Closed Principle (a1).

  2. 2.

    Zero-sum financial accounting invariant: Across all registered users, the sum of all net balances must always equal zero. If a dollar is credited to a payer, exactly that dollar must be debited across participants.

  3. 3.

    Decoupling expenses from settlement: Do not store directed edges between every pair of users for each bill. Track each user's single scalar net balance, then calculate settlement transactions on demand.

03

How to think through this problem (5-step walkthrough)

Step 1 Β· Scope the 45-minute target & core boundary

In a 45-minute LLD interview, the interviewer evaluates financial domain precision, strategy isolation, and debt simplification. Scope the design to: registering users, recording expenses across three split algorithms (Equal, Exact, Percent), storing all monetary balances strictly in integer paise (int64_t) to prevent floating-point drift, and computing simplified settlement transactions using a greedy min-cash-flow algorithm. Group hierarchies and multi-currency exchange can be deferred to follow-up questions.

Step 2 Β· Extract candidate nouns (and reject false classes)

Not every noun in the prompt deserves its own class. Separate dumb data structs from stateful managers, and turn trivial nouns into fields or enums.

User
Value Struct

Value struct representing an account holder with unique ID, display name, and contact information.

Split
Value Struct

Value struct binding a user ID to their allocated debt amount in integer paise (int64_t).

SplitStrategy
Abstract Interface

Strategy interface declaring calculateSplits(totalPaise, participants, values) to calculate individual user shares and validate split mathematical constraints.

SplitFactory
Stateful Class / Manager

Factory Method encapsulating strategy instantiation based on SplitType enum (EqualSplitStrategy, ExactSplitStrategy, PercentSplitStrategy), decoupling client callers from concrete calculation classes.

SplitwiseService
Stateful Class / Manager

Central ledger context managing registered users, recording expenses, updating net balance counters, and running greedy debt simplification.

CurrencySymbol / PercentageValue
Reject as Class β†’ Field / Method

Trap noun β€” do not create separate classes for currency symbols or percentages; currency formatting belongs in UI/presentation layers, and percentages are simple input values validated directly within PercentSplitStrategy.

Step 3 Β· Draft the naive design & spot what breaks

A naive implementation stores pairwise directed debts for every single bill (e.g. debts[alice][bob] += 50, debts[bob][alice] += 20). With dozens of shared meals and cab rides, a dense web of redundant reciprocal debts forms, making settlement messy and prone to cycles. Even worse, using double or float for money leads to floating-point representation drift (e.g. 0.333333 * 3 != 1.00), causing balance sheets to lose cents over time.

Step 4 Β· Map change hotspots to design patterns
Expense splitting calculation and validation rules (Equal vs Exact vs Percent)β†’ Strategy + Factory Method (SplitStrategy and SplitFactory)

A massive if-else or switch block in addExpense violates the Open-Closed Principle; adding a new split model (like shares or adjustments) risks breaking existing financial validation.

Debt settlement transactions across multiple participants→ Min-Cash-Flow Algorithm (Greedy matching on net balance graph)

Hardcoding pairwise bilateral settlements forces users to make unnecessary circular payments instead of settling net balances globally.

Step 5 Β· Lock down C++23 ownership, invariants & concurrency
  • βœ“

    Zero-sum financial accounting: Across all users in the system, the sum of all net balances must always equal zero ($\sum netBalance = 0$). Every rupee credited to the payer is precisely matched by rupees debited from the participants.

  • βœ“

    Integer arithmetic preservation: All financial operations use 64-bit integers representing paise (int64_t). For odd amounts in equal splits, remainder paise (totalPaise % n) are distributed one-by-one to early participants so no fractions are dropped.

  • βœ“

    Bounded settlement transactions: Greedy debt simplification processes N non-zero account holders in at most N-1 bilateral cash transfers by iteratively matching the largest debtor with the largest creditor.

04

Entities & design patterns used

Brute2Best Pro Content

Unlock Full UML Diagram & C++23 Solution

The complete UML diagram, production-ready C++23 code, follow-up extensions, and design pitfall analysis are part of Brute2Best Pro. All 7 foundation chapters are 100% free.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Systems Integration

Related C++ Systems & Algorithmic Foundations

Deep dive into underlying layers