Build a Social Payment Platform with Friend Connections
Data Structure DesignModel answerLast updated
Implement an in-memory system that handles user registration, friendship management, and peer-to-peer money transfers with proper validation.
You're building the core logic for a social payment platform. Your system must handle user accounts, friendship connections, and money transfers between friends.
Implement a class that supports these operations:
1. User Registration
- Create a new user account with a unique identifier and starting balance
- Each user tracks their current balance and their list of friends
2. Friendship Management
- Users can propose a friendship connection
- The proposal must be explicitly accepted before the friendship becomes active
- Each proposal gets a unique identifier
- When accepting, you reference the original proposal's ID (not the usernames again)
3. Money Transfers
- Users can send money to their friends
- Transfers are only valid between users who have an active friendship
- The sender must have sufficient funds
Constraints:
- All identifiers (for proposals, acceptances, and transfers) must be unique across the entire system
- Users cannot befriend themselves or send money to themselves
- Friendship is bidirectional—if A befriends B, then B is also friends with A
- A transfer fails if: users don't exist, they aren't friends, or the sender lacks funds
- Proposals cannot be sent to someone who is already a friend
- Each proposal can only be accepted once
- All balances are non-negative integers (representing smallest currency units)
- Transfer amounts must be positive
Your interface should support:
class SocialPaymentPlatform:
def add_user(self, user_id: str, starting_balance: int) -> bool:
# Returns False if user_id already exists or starting_balance is invalid
def propose_friendship(self, proposal_id: str, user_a: str, user_b: str) -> bool:
# Returns False if users don't exist, proposal_id is reused, or they're already friends
def confirm_friendship(self, confirmation_id: str, original_proposal_id: str) -> bool:
# Returns False if proposal doesn't exist, was already confirmed, or IDs are invalid
def send_money(self, transaction_id: str, sender: str, receiver: str, amount: int) -> bool:
# Returns False if users aren't friends, insufficient balance, or invalid parameters
Design your data structures to efficiently enforce all validation rules. Document your assumptions about edge cases.
Hints
Hint 1
Store friendship proposals separately from active friendships. The acceptance step is what creates the actual friendship relationship.
Hint 2
Use multiple hash maps: one for user objects, one for pending proposals, and a global set to track all used identifiers.
Hint 3
Validate everything before making any state changes. This ensures each operation is atomic—it either fully succeeds or leaves the state unchanged.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Approach
This problem tests your ability to model stateful business logic with proper validation. The key insight is recognizing the two-phase friendship model: proposals are stored separately, and friendships only become active when confirmed.
Core Design Decisions:
-
Shared identifier namespace: All IDs (proposals, confirmations, transactions) come from one global pool. An ID is marked as used only when its operation succeeds, allowing retries with the same ID after failures.
-
Self-operations: Reject attempts to befriend yourself or transfer to yourself.
-
Duplicate friendships: If users are already friends, new proposals between them should fail.
-
Bidirectional storage: When a friendship is confirmed, add each user to the other's friend set for O(1) lookup during transfers.
-
Validation order: Check all preconditions before modifying any state. This makes operations atomic—no partial updates on failure.
Data Structures:
users: dict[str, User] # User objects with balance and friends set
proposals: dict[str, Proposal] # Pending friendship proposals
used_ids: set[str] # Global identifier tracking
completed_transfers: dict[str, Transfer] # Optional audit log
The indirection in the confirmation step is handled by storing the proposal: confirm_friendship takes only original_proposal_id, looks it up in the proposals dictionary, retrieves the two users, and updates both their friend sets.
Implementation
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class User:
user_id: str
balance: int
friends: set[str] = field(default_factory=set)
@dataclass
class Proposal:
proposal_id: str
user_a: str
user_b: str
confirmed: bool = False
class SocialPaymentPlatform:
def __init__(self):
self.users: dict[str, User] = {}
self.proposals: dict[str, Proposal] = {}
self.used_ids: set[str] = set()
self.completed_transfers: dict[str, tuple[str, str, int]] = {}
def add_user(self, user_id: str, starting_balance: int) -> bool:
# Validate before mutating
if not user_id or user_id in self.users:
return False
if not isinstance(starting_balance, int) or isinstance(starting_balance, bool):
return False
if starting_balance < 0:
return False
# Create user
self.users[user_id] = User(user_id, starting_balance)
return True
def propose_friendship(self, proposal_id: str, user_a: str, user_b: str) -> bool:
# Validate all preconditions
if not proposal_id or proposal_id in self.used_ids:
return False
if user_a not in self.users or user_b not in self.users:
return False
if user_a == user_b:
return False
# Check if already friends
if user_b in self.users[user_a].friends:
return False
# Store proposal and mark ID as used
self.proposals[proposal_id] = Proposal(proposal_id, user_a, user_b)
self.used_ids.add(proposal_id)
return True
def confirm_friendship(self, confirmation_id: str, original_proposal_id: str) -> bool:
# Validate confirmation ID
if not confirmation_id or confirmation_id in self.used_ids:
return False
# Look up original proposal
if original_proposal_id not in self.proposals:
return False
proposal = self.proposals[original_proposal_id]
# Check if already confirmed
if proposal.confirmed:
return False
# Verify users still exist
if proposal.user_a not in self.users or proposal.user_b not in self.users:
return False
# Mark as confirmed and establish bidirectional friendship
proposal.confirmed = True
self.users[proposal.user_a].friends.add(proposal.user_b)
self.users[proposal.user_b].friends.add(proposal.user_a)
self.used_ids.add(confirmation_id)
return True
def send_money(self, transaction_id: str, sender: str, receiver: str, amount: int) -> bool:
# Validate transaction ID
if not transaction_id or transaction_id in self.used_ids:
return False
# Validate users exist
if sender not in self.users or receiver not in self.users:
return False
# Validate amount
if not isinstance(amount, int) or isinstance(amount, bool):
return False
if amount <= 0:
return False
# Check self-transfer
if sender == receiver:
return False
# Verify friendship
if receiver not in self.users[sender].friends:
return False
# Check sufficient balance
sender_user = self.users[sender]
if sender_user.balance < amount:
return False
# Execute transfer atomically
sender_user.balance -= amount
self.users[receiver].balance += amount
self.used_ids.add(transaction_id)
self.completed_transfers[transaction_id] = (sender, receiver, amount)
return True
Why This Works
Friendship symmetry: Only confirm_friendship writes to friend sets, and it always adds both directions simultaneously. This guarantees user_b in users[user_a].friends ⟺ user_a in users[user_b].friends.
No double-confirmation: The confirmed flag prevents re-confirming the same proposal. The confirmation's own ID is also consumed, preventing replay of the acceptance.
Balance conservation: Validation completes before any mutation. The debit and credit happen back-to-back with no intermediate checks that could fail, so the sum of all balances remains constant.
No overdrafts: We check balance >= amount before subtraction, and amount is guaranteed positive, so balances never go negative.
Complexity
- Time: O(1) expected for all operations (hash table lookups and set operations)
- Space: O(U + F + R) where U = users, F = friendships (stored bidirectionally), R = requests/transactions
Common Edge Cases
- Negative or zero starting balance: Reject on registration
- Invalid amounts: Zero, negative, or non-integer values in transfers
- Reused identifiers: Each ID can only succeed once
- Self-operations: Friending or paying yourself
- Nonexistent users: Referenced users must exist
- Missing friendship: Cannot transfer without confirmed friendship
- Insufficient funds: Balance must be at least the transfer amount
- Exact balance transfer: Should succeed (balance becomes zero)
- Already friends: New proposal should fail, but confirming a pending proposal after becoming friends via another route could be allowed (mark confirmed, no state change)
Thread Safety Extension
For concurrent access, wrap each public method's body in a lock:
from threading import Lock
def __init__(self):
# ... existing initialization ...
self._lock = Lock()
def add_user(self, user_id: str, starting_balance: int) -> bool:
with self._lock:
# ... existing logic ...
This makes each operation atomic under concurrent access. For higher throughput, consider finer-grained locking (per-user locks) or optimistic concurrency with versioning.