Bird
Raised Fist0
LLDsystem_design~25 mins

User, Group, Expense classes in LLD - System Design Exercise

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Design: Expense Sharing System
Design the core classes User, Group, and Expense with their relationships and basic methods. Out of scope: UI, payment integration, notifications.
Functional Requirements
FR1: Users can create and join groups.
FR2: Users can add expenses to groups.
FR3: Each expense has a payer and multiple participants.
FR4: The system tracks who owes whom and how much.
FR5: Users can view their balance within each group.
Non-Functional Requirements
NFR1: Support up to 10,000 users and 1,000 groups.
NFR2: Expense addition and balance calculation latency under 200ms.
NFR3: System availability 99.9%.
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
User class with user details and group memberships
Group class managing members and expenses
Expense class capturing amount, payer, participants, and splits
Design Patterns
Aggregation pattern for Group containing Users and Expenses
Observer pattern if notifications are needed (out of scope here)
Factory pattern for creating Expense instances with validation
Reference Architecture
User <-- belongs to -- Group <-- contains -- Expense

User:
  - id
  - name
  - groups

Group:
  - id
  - name
  - members (Users)
  - expenses

Expense:
  - id
  - description
  - amount
  - payer (User)
  - participants (Users)
  - splits (map User to amount)
Components
User
Class in any OOP language
Represents a user with identity and group memberships
Group
Class in any OOP language
Represents a group of users sharing expenses
Expense
Class in any OOP language
Represents an expense with payer, participants, and split amounts
Request Flow
1. User creates a Group or joins an existing Group.
2. User adds an Expense to a Group specifying payer, participants, and amount.
3. Group stores the Expense and updates balances for involved Users.
4. Users query Group to get their current balance and owed amounts.
Database Schema
Entities: - User(id PK, name) - Group(id PK, name) - UserGroup(user_id FK, group_id FK) // many-to-many - Expense(id PK, group_id FK, description, amount, payer_id FK) - ExpenseParticipant(expense_id FK, user_id FK, amount) Relationships: - User to Group is many-to-many via UserGroup - Group to Expense is one-to-many - Expense to ExpenseParticipant is one-to-many - ExpenseParticipant links Users to their share in an Expense
Scaling Discussion
Bottlenecks
Calculating balances for large groups with many expenses can be slow.
Storing and querying many-to-many relationships between users and groups.
Handling concurrent expense additions causing race conditions.
Solutions
Cache computed balances per user per group and update incrementally on expense changes.
Use indexed join tables and optimized queries for UserGroup and ExpenseParticipant.
Use transactions or optimistic locking to handle concurrent updates safely.
Interview Tips
Time: 10 minutes for requirements and clarifications, 15 minutes for class design and relationships, 10 minutes for scaling and trade-offs discussion.
Clarify assumptions about group membership and expense splitting.
Explain class responsibilities and relationships clearly.
Discuss how to keep balances updated efficiently.
Mention concurrency and data consistency considerations.
Show awareness of scaling challenges and solutions.

Practice

(1/5)
1. Which class is primarily responsible for storing information about individual people in a shared expense system?
easy
A. Payment
B. User
C. Expense
D. Group

Solution

  1. Step 1: Understand the role of each class

    User class represents individual people, Group holds multiple users, Expense tracks costs.
  2. Step 2: Identify which class stores individual info

    User class stores personal details like name and ID for each person.
  3. Final Answer:

    User -> Option B
  4. Quick Check:

    User = Individual person [OK]
Hint: User class = individual person info [OK]
Common Mistakes:
  • Confusing Group with User
  • Thinking Expense stores user details
  • Assuming Payment is a class here
2. Which of the following is the correct way to define a Group class that holds multiple User objects in Python?
easy
A. class Group: def __init__(self): self.users = []
B. class Group: def __init__(self): self.user = {}
C. class Group: def __init__(self): self.expenses = []
D. class Group: def __init__(self): self.members = None

Solution

  1. Step 1: Identify correct attribute for multiple users

    A list is suitable to hold multiple User objects, so self.users = [] is correct.
  2. Step 2: Check other options for correctness

    class Group: def __init__(self): self.user = {} uses a dict named user which is not typical for holding users; class Group: def __init__(self): self.expenses = [] uses expenses which belongs to Expense class; class Group: def __init__(self): self.members = None sets members to None which is not a collection.
  3. Final Answer:

    class Group: def __init__(self): self.users = [] -> Option A
  4. Quick Check:

    Group holds list of users = self.users = [] [OK]
Hint: Group holds list of users with self.users = [] [OK]
Common Mistakes:
  • Using dict instead of list for users
  • Confusing expenses with users
  • Initializing members as None instead of a list
3. Given the following code snippet, what will be the output?
class Expense:
    def __init__(self, amount, paid_by, split_between):
        self.amount = amount
        self.paid_by = paid_by
        self.split_between = split_between

    def split_amount(self):
        return self.amount / len(self.split_between)

expense = Expense(120, 'Alice', ['Alice', 'Bob', 'Charlie'])
print(expense.split_amount())
medium
A. Error
B. 60
C. 120
D. 40.0

Solution

  1. Step 1: Understand the split_amount method

    It divides total amount by number of people in split_between list.
  2. Step 2: Calculate the split

    Amount = 120, split_between has 3 people, so 120 / 3 = 40.0.
  3. Final Answer:

    40.0 -> Option D
  4. Quick Check:

    120 divided by 3 = 40.0 [OK]
Hint: Divide amount by count of split_between list [OK]
Common Mistakes:
  • Forgetting to divide by number of people
  • Dividing by 2 instead of 3
  • Assuming paid_by affects split amount
4. Identify the bug in this Expense class method that calculates each user's share:
class Expense:
    def __init__(self, amount, paid_by, split_between):
        self.amount = amount
        self.paid_by = paid_by
        self.split_between = split_between

    def split_amount(self):
        return self.amount // len(self.split_between)
medium
A. Using integer division (//) may lose cents in split
B. split_between should be a dictionary, not a list
C. paid_by should be a list, not a single user
D. amount should be a string, not a number

Solution

  1. Step 1: Analyze the division operator used

    The method uses integer division (//) which truncates decimals.
  2. Step 2: Understand impact on money split

    Using // can lose fractional cents, causing inaccurate splits.
  3. Final Answer:

    Using integer division (//) may lose cents in split -> Option A
  4. Quick Check:

    Integer division truncates decimals, causing loss [OK]
Hint: Use float division (/) for accurate money splits [OK]
Common Mistakes:
  • Ignoring decimal loss from integer division
  • Confusing data types for paid_by or split_between
  • Thinking amount should be string
5. You want to design a system where multiple users in a group can add expenses, and the system automatically calculates how much each user owes or is owed. Which design approach best supports scalability and clear responsibility?
hard
A. Make User class handle all expense calculations and group management to centralize logic
B. Use only a single Expense class that stores all users and groups inside it to simplify design
C. Create User, Group, and Expense classes where Group manages users and expenses; Expense tracks amount and split; User tracks individual balances updated by Group
D. Store all data in a flat file and calculate splits manually each time without classes

Solution

  1. Step 1: Identify responsibilities for each class

    User holds personal info and balances, Group manages users and expenses, Expense tracks costs and splits.
  2. Step 2: Evaluate design for scalability and clarity

    Create User, Group, and Expense classes where Group manages users and expenses; Expense tracks amount and split; User tracks individual balances updated by Group cleanly separates concerns, making it easier to maintain and scale.
  3. Final Answer:

    Create User, Group, and Expense classes where Group manages users and expenses; Expense tracks amount and split; User tracks individual balances updated by Group -> Option C
  4. Quick Check:

    Clear class roles = scalable design [OK]
Hint: Separate concerns: User, Group, Expense each handle distinct roles [OK]
Common Mistakes:
  • Putting all logic in one class
  • Ignoring separation of concerns
  • Using flat files for complex data