This question evaluates object-oriented design skills, stateful in-memory data structures, request processing, and correctness constraints such as friend relationships, unique request IDs, and atomic balance transfers.
Design and implement an in-memory payment system with simple social features. The system processes a sequence of requests that can:
user_id
(string)
balance
(integer amount, e.g., cents)
req_id
for this friend request
user1
and
user2
(both must be existing users)
req_id
(unique for the accept request)
req_id
of the original friend request to accept
user1
and
user2
become friends.
req_id
from_user
to_user
amount
(> 0)
from_user
does not have enough balance.
amount
from
from_user.balance
.
amount
to
to_user.balance
.
Design classes and methods in an object-oriented way.
One possible interface (you can adjust names/signatures as long as behavior is clear):
class PaymentSystem:
def register_user(self, user_id: str, initial_balance: int) -> bool:
"""Register a new user with given balance. Return False if user_id already exists."""
def send_friend_request(self, req_id: str, user1: str, user2: str) -> bool:
"""Store a friend request identified by req_id. Return False on invalid input or duplicate req_id."""
def accept_friend_request(self, req_id: str, original_req_id: str) -> bool:
"""Accept the previously stored friend request with ID original_req_id. Return False if original_req_id doesn't exist, is already accepted, or users are invalid."""
def transfer(self, req_id: str, from_user: str, to_user: str, amount: int) -> bool:
"""Transfer amount from from_user to to_user if they are friends and balance is sufficient. Return True on success, False otherwise."""
Your implementation should:
req_id
.
You may ignore concurrency in the basic solution, but you can optionally comment on how you would make operations atomic under multiple threads.