Single-Channel Two-Party Call Manager With Custom Exceptions
Medium · Coding & Algorithms · Software Engineer · HR Screen
Problem Statement
Build a single-line, two-party call controller where at most one conversation can take place at a time. Provide Caller (exposing a .name string attribute), a custom CommunicationException(Exception) initialized with an error message string, an abstract interface CommsHandlerABC, its concrete implementation CommsHandler(CommsHandlerABC), and the replay function run_comms_handler:
class Caller:
def __init__(self, name: str) -> None: ...
class CommunicationException(Exception):
def __init__(self, message: str) -> None: ...
class CommsHandlerABC(ABC):
@abstractmethod
def connect(self, user1: Caller, user2: Caller) -> str: ...
@abstractmethod
def hangup(self, user1: Caller, user2: Caller) -> str: ...
@abstractmethod
def clear_all(self) -> None: ...
class CommsHandler(CommsHandlerABC): ...
def run_comms_handler(
operations: List[str], arguments: List[List[Dict[str, str]]]
) -> List[Optional[str]]:
Method Specifications
Callers are compared by their .name string (user1.name == user2.name denotes the same participant).
connect(user1, user2) -> str- Self-call check (evaluated first, even when a call is active): if
user1.name == user2.name, raiseCommunicationException(f"{user1.name} cannot connect with {user2.name}"). - Busy-channel check: otherwise, if the channel already holds an active pair (including
(user1, user2)themselves), raiseCommunicationException("Connection in use. Please try later"). - Success: record
{user1.name, user2.name}as the active call and returnf"Connection established between {user1.name} and {user2.name}".
- Self-call check (evaluated first, even when a call is active): if
hangup(user1, user2) -> str- Self-hangup check (evaluated first): if
user1.name == user2.name, raiseCommunicationException(f"{user1.name} cannot hangup with {user2.name}"). - Active-pair check: otherwise, if
{user1.name, user2.name}does not match both participants currently occupying the channel (either the channel is idle or at least one name differs), keep any active call intact and raiseCommunicationException(f"{user1.name} and {user2.name} not found in the communication channel"). - Success: release the channel (accepting the connected pair in either argument order) and return
f"{user1.name} and {user2.name} are disconnected".
- Self-hangup check (evaluated first): if
clear_all() -> None- Reset the channel to idle regardless of whether a call is underway, returning
None.
- Reset the channel to idle regardless of whether a call is underway, returning
run_comms_handler(operations, arguments)- Replay
operationssequentially against a singleCommsHandlerinstance ("clear_all"takes[]and appendsNone;"connect"and"hangup"take[{"name": n1}, {"name": n2}]and append the returned string, or"EXCEPTION: " + messagewheneverCommunicationExceptionis raised).
- Replay
Examples
Example 1
Input:
operations = ["connect", "hangup", "connect"]
arguments = [
[{"name": "Maya"}, {"name": "Liam"}],
[{"name": "Liam"}, {"name": "Maya"}],
[{"name": "Noah"}, {"name": "Zoe"}]
]
Output:
[
"Connection established between Maya and Liam",
"Liam and Maya are disconnected",
"Connection established between Noah and Zoe"
]
Walk-through: Maya and Liam occupy the idle line, Liam hangs up in reverse argument order (freeing the line while keeping hangup's caller order in the message), and Noah and Zoe can then connect.
Example 2
Input:
operations = ["connect", "connect", "hangup", "clear_all", "connect"]
arguments = [
[{"name": "Maya"}, {"name": "Liam"}],
[{"name": "Noah"}, {"name": "Zoe"}],
[{"name": "Maya"}, {"name": "Noah"}],
[],
[{"name": "Noah"}, {"name": "Zoe"}]
]
Output:
[
"Connection established between Maya and Liam",
"EXCEPTION: Connection in use. Please try later",
"EXCEPTION: Maya and Noah not found in the communication channel",
None,
"Connection established between Noah and Zoe"
]
Walk-through: While Maya and Liam hold the line, Noah and Zoe receive the busy error, and hangup(Maya, Noah) fails without dropping Maya and Liam's call because Noah is not on the line. clear_all() resets the line to idle (None), allowing Noah and Zoe to connect.
Example 3
Input:
operations = ["hangup", "connect", "connect"]
arguments = [
[{"name": "Maya"}, {"name": "Maya"}],
[{"name": "Maya"}, {"name": "Liam"}],
[{"name": "Noah"}, {"name": "Noah"}]
]
Output:
[
"EXCEPTION: Maya cannot hangup with Maya",
"Connection established between Maya and Liam",
"EXCEPTION: Noah cannot connect with Noah"
]
Walk-through: Self-hangup raises on an idle channel, Maya and Liam connect, and connect(Noah, Noah) raises the self-call error even while the channel is occupied.
Constraints
0 <= len(operations) == len(arguments) <= 10^4.- Every element of
operationsis"connect","hangup", or"clear_all". - Every caller object provides a non-empty string
.nameattribute. - Each method on
CommsHandlerruns inO(1)time andO(1)space (treating caller name length as bounded).
Step-by-step walkthrough
Understand the components and rules
We are building a single-channel phone line where at most one pair of callers can talk at a time:
CommunicationException(Exception): a custom exception initialized with an error message string.CommsHandler(CommsHandlerABC):connect(user1, user2)-> raises ifuser1.name == user2.name, raises if the channel is already occupied, or connects the pair and returns a confirmation string.hangup(user1, user2)-> raises ifuser1.name == user2.name, raises"{user1.name} and {user2.name} not found in the communication channel"(leaving any ongoing call intact) if they do not match the active pair, or disconnects them in either argument order and returns a confirmation string.clear_all()-> frees the channel unconditionally and returnsNone.
run_comms_handler(operations, arguments): replays a sequence of calls against oneCommsHandlerand records each return value (or"EXCEPTION: " + messagewheneverCommunicationExceptionis raised).
Model the channel as a two-state machine
Because only one conversation can happen at a time and rejected callers are never queued, the entire handler has just two states: idle or occupied by one unordered pair of names.
connect(u1, u2) [u1 != u2, line free] +-----------+ -------------------------> +------------------------+ | FREE | | IN USE | | None | <------------------------- | {"Maya", "Liam"} | +-----------+ hangup(Maya, Liam) or +------------------------+ ^ | hangup(Liam, Maya) or | | | clear_all() | +-------+ v clear_all() -> None any other connect / bad hangup bad connect / hangup -> raise -> raise (state stays {"Maya", "Liam"})Why store a set of two strings
{"Maya", "Liam"}instead of a tuple ofCallerobjects? 1. Identity by name: TwoCaller("Maya")instances are distinct Python objects in memory, so comparinguser1 == user2would miss self-calls unless we compare.name. 2. Order independence: Python sets ignore order, so{"Liam", "Maya"} == {"Maya", "Liam"}evaluates toTrue. That lets Liam hang up a call initiated by Maya with a single==check.class CommsHandler(CommsHandlerABC): def __init__(self) -> None: # active_pair: unordered 2-element set of caller names, e.g. {"Maya", "Liam"}, # or None when the single communication channel is free. self.active_pair: Optional[Set[str]] = None def _is_active_pair(self, user1: Caller, user2: Caller) -> bool: """Return True if user1 and user2 are the connected pair, in either order.""" if self.active_pair is None: return False # Set comparison ignores argument order: {"Liam", "Maya"} == {"Maya", "Liam"}. return self.active_pair == {user1.name, user2.name}Define `Caller`, `CommunicationException`, and `CommsHandlerABC`
Since our file runs standalone in the judge, we define clean, minimal versions of
CallerandCommsHandlerABCalongsideCommunicationException.Passing
messagetosuper().__init__(message)ensuresstr(error)returns the message as standard Python code expects, while savingself.message = messagemakes reading it explicit. Marking the three interface methods with@abstractmethodmakes Python enforce thatCommsHandlerimplements all three before it can be instantiated.class Caller: """Represents a user on the communication system (identified by name).""" def __init__(self, name: str) -> None: self.name = name class CommunicationException(Exception): """Domain exception raised when a connect or hangup rule is violated.""" def __init__(self, message: str) -> None: # Pass message to Exception so str(error) returns it directly. super().__init__(message) self.message = message class CommsHandlerABC(ABC): """Abstract interface requiring connect, hangup, and clear_all.""" @abstractmethod def connect(self, user1: Caller, user2: Caller) -> str: pass @abstractmethod def hangup(self, user1: Caller, user2: Caller) -> str: pass @abstractmethod def clear_all(self) -> None: passImplement `connect` with validation in exact priority order
Check the validation precedence inside
connectcarefully: 1. First testuser1.name == user2.nameand raise"{user1.name} cannot connect with {user2.name}". 2. Only when the two callers are distinct, testself.active_pair is not Noneand raise"Connection in use. Please try later".That ordering matters! If Maya and Liam are currently talking and Noah dials himself (
connect(Noah, Noah)), as in Example 3, we must raise"Noah cannot connect with Noah", not"Connection in use. Please try later". Meanwhile, if Maya and Liam callconnect(Maya, Liam)a second time while already talking, their names differ andself.active_pairis occupied, so"Connection in use. Please try later"is raised naturally.We assign
self.active_paironly after both checks pass so a failed call can never corrupt the channel state.def connect(self, user1: Caller, user2: Caller) -> str: # Phase 1: Check same-user rule BEFORE busy-line rule because the busy error # applies only when two distinct callers attempt to claim an occupied line. if user1.name == user2.name: raise CommunicationException( f"{user1.name} cannot connect with {user2.name}" ) # Phase 2: Reject any connection attempt while the single channel is occupied # (including a duplicate connect call from the pair already on the line). if self.active_pair is not None: raise CommunicationException("Connection in use. Please try later") # Phase 3: Mutate state only after all validation checks succeed. self.active_pair = {user1.name, user2.name} return f"Connection established between {user1.name} and {user2.name}"Implement `hangup` and `clear_all`
hangupfollows the exact same defensive pattern: 1. Checkuser1.name == user2.namefirst so self-hangup always reports"{name} cannot hangup with {name}". 2. Checkself._is_active_pair(user1, user2). Both names must match! If Maya and Liam are talking and someone callshangup(Maya, Noah),{"Maya", "Noah"} != {"Maya", "Liam"}, so we raise without dropping Maya and Liam's call. 3. Setself.active_pair = Noneand format the disconnect string using{user1.name}first and{user2.name}second — even ifhangup(Liam, Maya)reversed the originalconnect(Maya, Liam)order.clear_allsimply resetsself.active_pair = Nonewhether the channel was occupied or already idle.def hangup(self, user1: Caller, user2: Caller) -> str: # Phase 1: Reject hanging up a user with themselves regardless of channel state. if user1.name == user2.name: raise CommunicationException( f"{user1.name} cannot hangup with {user2.name}" ) # Phase 2: Ensure both users match the active call so an unrelated user # (e.g. hangup(Maya, Noah)) cannot accidentally drop Maya and Liam's call. if not self._is_active_pair(user1, user2): raise CommunicationException( f"{user1.name} and {user2.name} not found in the communication channel" ) # Phase 3: Free the channel and preserve the caller order passed to hangup. self.active_pair = None return f"{user1.name} and {user2.name} are disconnected" def clear_all(self) -> None: # Unconditionally reset the channel to free, even if already None. self.active_pair = NoneWire up the `run_comms_handler` adapter and trace Example 2
The judge passes parallel lists
operationsandarguments. For"clear_all",arguments[i]is empty[]and we appendNone. For"connect"and"hangup", we wrap the two input dicts inCallerobjects, invoke the method inside atryblock, and catch onlyCommunicationException(so genuine bugs like typos orKeyErrorare never hidden).Let's trace Example 2 step by step to verify every state transition:
Step Operation active_pair before Outcome / active_pair after ---- ---------------------- ------------------- --------------------------------------------------------------- 1 connect(Maya, Liam) None "Connection established between Maya and Liam" -> active_pair = {"Maya", "Liam"} 2 connect(Noah, Zoe) {"Maya", "Liam"} raises -> "EXCEPTION: Connection in use. Please try later" -> active_pair stays {"Maya", "Liam"} 3 hangup(Maya, Noah) {"Maya", "Liam"} raises -> "EXCEPTION: Maya and Noah not found in the communication channel" -> active_pair stays {"Maya", "Liam"} 4 clear_all() {"Maya", "Liam"} None -> active_pair = None 5 connect(Noah, Zoe) None "Connection established between Noah and Zoe" -> active_pair = {"Noah", "Zoe"}Full solution
Putting all classes and the judge adapter together gives the complete solution:
from typing import Any, Dict, List, Optional, Set, Tuple from abc import ABC, abstractmethod class Caller: """Represents a user on the communication system (identified by name).""" def __init__(self, name: str) -> None: self.name = name class CommunicationException(Exception): """Domain exception raised when a connect or hangup rule is violated.""" def __init__(self, message: str) -> None: # Pass message to Exception so str(error) returns it directly. super().__init__(message) self.message = message class CommsHandlerABC(ABC): """Abstract interface requiring connect, hangup, and clear_all.""" @abstractmethod def connect(self, user1: Caller, user2: Caller) -> str: pass @abstractmethod def hangup(self, user1: Caller, user2: Caller) -> str: pass @abstractmethod def clear_all(self) -> None: pass class CommsHandler(CommsHandlerABC): def __init__(self) -> None: # active_pair: unordered 2-element set of caller names, e.g. {"Maya", "Liam"}, # or None when the single communication channel is free. self.active_pair: Optional[Set[str]] = None def _is_active_pair(self, user1: Caller, user2: Caller) -> bool: """Return True if user1 and user2 are the connected pair, in either order.""" if self.active_pair is None: return False # Set comparison ignores argument order: {"Liam", "Maya"} == {"Maya", "Liam"}. return self.active_pair == {user1.name, user2.name} def connect(self, user1: Caller, user2: Caller) -> str: # Phase 1: Check same-user rule BEFORE busy-line rule because the busy error # applies only when two distinct callers attempt to claim an occupied line. if user1.name == user2.name: raise CommunicationException( f"{user1.name} cannot connect with {user2.name}" ) # Phase 2: Reject any connection attempt while the single channel is occupied # (including a duplicate connect call from the pair already on the line). if self.active_pair is not None: raise CommunicationException("Connection in use. Please try later") # Phase 3: Mutate state only after all validation checks succeed. self.active_pair = {user1.name, user2.name} return f"Connection established between {user1.name} and {user2.name}" def hangup(self, user1: Caller, user2: Caller) -> str: # Phase 1: Reject hanging up a user with themselves regardless of channel state. if user1.name == user2.name: raise CommunicationException( f"{user1.name} cannot hangup with {user2.name}" ) # Phase 2: Ensure both users match the active call so an unrelated user # (e.g. hangup(Maya, Noah)) cannot accidentally drop Maya and Liam's call. if not self._is_active_pair(user1, user2): raise CommunicationException( f"{user1.name} and {user2.name} not found in the communication channel" ) # Phase 3: Free the channel and preserve the caller order passed to hangup. self.active_pair = None return f"{user1.name} and {user2.name} are disconnected" def clear_all(self) -> None: # Unconditionally reset the channel to free, even if already None. self.active_pair = None def run_comms_handler( operations: List[str], arguments: List[List[Dict[str, str]]] ) -> List[Optional[str]]: handler = CommsHandler() # results: one entry per operation (return string, None, or "EXCEPTION: <msg>") results: List[Optional[str]] = [] for op, args in zip(operations, arguments): if op == "clear_all": handler.clear_all() results.append(None) continue if op != "connect" and op != "hangup": raise ValueError(f"unknown operation: {op}") user1 = Caller(args[0]["name"]) user2 = Caller(args[1]["name"]) # Catch only CommunicationException so unexpected bugs still surface cleanly. try: if op == "connect": outcome = handler.connect(user1, user2) else: outcome = handler.hangup(user1, user2) results.append(outcome) except CommunicationException as error: results.append("EXCEPTION: " + error.message) return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of CommsHandler like an old-fashioned single-line walkie-talkie channel shared by an office: either the channel is silent (None), or two people have claimed it ({"Maya", "Liam"}), and nobody else can talk until those two hang up or an operator hits the master reset button (clear_all). Under the hood, this is a tiny state machine (an object that keeps its current status in one variable and lets methods move it cleanly from one valid status to another), paired with an abstract base class (ABC) (a blueprint class that lists required methods so Python refuses to create any subclass that forgets to implement one) and a custom exception (a specialized subclass of Exception so callers can catch expected domain errors without accidentally hiding unrelated bugs).
Why do quick-and-dirty implementations trip up here? First, comparing Caller objects with user1 == user2 or is fails because two separate Caller("Maya") instances live at different memory addresses even though they represent the same person. Second, storing an ordered tuple (user1.name, user2.name) and checking only exact tuple equality breaks when Liam hangs up a call that Maya initiated (hangup(Liam, Maya)). Third, checking whether the channel is busy before checking whether someone is calling themselves reports the wrong error message when Noah dials Noah during an active Maya-Liam call.
Let's walk through four calls to see how self.active_pair (an unordered set of two names, or None) handles all three traps cleanly:
Initial state: active_pair = None
1. connect(Maya, Liam) -> names differ, line is None
-> active_pair = {"Maya", "Liam"}
-> returns "Connection established between Maya and Liam"
2. connect(Noah, Noah) -> checked FIRST: "Noah" == "Noah"
-> raises CommunicationException("Noah cannot connect with Noah")
-> active_pair stays {"Maya", "Liam"}
3. hangup(Liam, Maya) -> {"Liam", "Maya"} == {"Maya", "Liam"} matches!
-> active_pair = None
-> returns "Liam and Maya are disconnected" (keeps hangup's order)
4. clear_all() -> active_pair = None
-> returns None
Complexity
Let M be the number of operations in operations (assuming caller names have bounded length; if name length L can grow arbitrarily, hashing or comparing a name takes O(L) time).
- Time:
O(1)perconnect,hangup, orclear_allcall, andO(M)total across theMoperations. Each method compares at most two string names and builds or compares a two-element set, doing a constant amount of work per operation. - Space:
O(1)insideCommsHandlerbecauseself.active_pairholds eitherNoneor a set of two strings at all times, plusO(M)inrun_comms_handlerto store the output list ofMresults.
Edge cases
- Same user passed twice (
connect(Maya, Maya)orhangup(Maya, Maya)): Raises the self-connect or self-hangupCommunicationExceptionimmediately, even when another pair is currently using the channel (Example 3). - Already-connected pair calls
connectagain (connect(Maya, Liam)orconnect(Liam, Maya)): Because the channel is already occupied and the two callers are distinct, it raises"Connection in use. Please try later". - Reverse-order
hangup(connect(Maya, Liam)followed byhangup(Liam, Maya)): Succeeds because set equality{"Liam", "Maya"} == {"Maya", "Liam"}is order-independent, while the returned string preserves thehangupargument order ("Liam and Maya are disconnected", Example 1). - Partial match on
hangup(hangup(Maya, Noah)while Maya and Liam are talking): Raises"Maya and Noah not found in the communication channel"and leaves Maya and Liam connected (Example 2). clear_allon an already free channel: Safely leavesself.active_pairasNoneand returnsNonewithout raising.- Duck-typed caller objects: Using duck typing (reading
.namedirectly rather than checkingisinstance(user, Caller)) lets any caller object with a.nameattribute work seamlessly. - Empty operation list (
[]): Returns[]without touching the handler.
Common mistakes
- Checking
self.active_pair is not Nonebeforeuser1.name == user2.name: Causesconnect(Noah, Noah)during an active call to raise"Connection in use. Please try later"instead of"Noah cannot connect with Noah". - Comparing
user1 == user2instead ofuser1.name == user2.name: Default object equality in Python checks object identity (is), so two separateCaller("Maya")instances appear "different" and Example 3 fails. - Dropping the active call when only one user in
hangupmatches: Checkinguser1.name in self.active_pair or user2.name in self.active_pairletshangup(Maya, Noah)cut off Maya and Liam's conversation. - Mutating
self.active_pairbefore all validation passes: Leaves the channel corrupted after a raised exception. - Using bare
except Exception:in the adapter: Swallows real programming bugs (such asAttributeErrororKeyError) and disguises them as expected test outputs. - Subtle string typos: Writing
"hang up"instead of"hangup"or adding a trailing period to"Connection in use. Please try later"fails exact string assertions.
Alternative approaches
- Store a 2-tuple of names
(user1.name, user2.name): EquallyO(1)time and space, and avoids building a tiny set, at the minor cost of writing(a, b) == self.active_pair or (b, a) == self.active_pairinside_is_active_pair. - Define
__eq__and__hash__onCallerbyname: Allows storingfrozenset({user1, user2}), though in interviews whereCalleris provided externally by the test suite, you cannot modifyCallerand comparing.nameis safer.
Follow-up questions
- How would you make CommsHandler safe when multiple threads invoke connect, hangup, and clear_all concurrently? Right now
connectsuffers from a check-then-act race condition (a concurrency bug where two threads both seeself.active_pair is Noneat the same instant and both overwriteself.active_pair, silently dropping the first call). Addself._lock = threading.Lock()in__init__and wrap the body ofconnect,hangup, andclear_allinsidewith self._lock:so checking and updatingself.active_pairhappen as one indivisible step; Python'swithblock automatically releases the lock even whenCommunicationExceptionis raised. - How would you generalize the design to allow up to K simultaneous two-party calls while keeping operations O(1)? Replace
self.active_pairwith a dictionaryself.partner_of: Dict[str, str] = {}mapping each busy caller's name to the name of the person they are talking to, so the number of active calls islen(self.partner_of) // 2. Inconnect(u1, u2), checku1 != u2, check that neitheru1noru2is already inself.partner_of, and checklen(self.partner_of) // 2 < Kbefore settingself.partner_of[u1] = u2andself.partner_of[u2] = u1;hangupverifiesself.partner_of.get(u1) == u2and deletes both keys, keepingconnectandhangupO(1)average time (clear_all()simply callsself.partner_of.clear()). - Why raise a dedicated CommunicationException class rather than returning error message strings from connect and hangup? Returning error strings mixes failure messages into the exact same
strreturn type as normal status messages, forcing every caller to parse text like"cannot connect"to tell whether a call succeeded. RaisingCommunicationExceptionseparates normal control flow from error handling, and in a larger codebase you can subclass it intoSameUserError(CommunicationException)andLineBusyError(CommunicationException)so callers can retry onLineBusyErrorwhile still catching all communication errors viaCommunicationException.
Follow-up questions
- How would you make CommsHandler safe when multiple threads invoke connect, hangup, and clear_all concurrently?
- How would you generalize the design to allow up to K simultaneous two-party calls while keeping operations O(1)?
- Why raise a dedicated CommunicationException class rather than returning error message strings from connect and hangup?
Similar questions
- Net Portfolio Deltas by Asset Group
- Optimal Multi-Symbol Trading Plan
- Fewest Operations to Reach Target Integer
- Subarrays Summing to Target
- Fewest Index Swaps to Sort with Duplicates
- Bottom-Up Max-Heap Construction
More Akuna Capital interview questions
- Multi-Tier Weighted Cache With TTL Expiration Hard
- Limit Order Book Matching Engine Hard
- Hexadecimal String Bitwise AND Medium Pro
- Maximum Node Value in an Unordered Binary Tree Medium Pro
- Single-Channel Two-Party Call Controller Medium Pro
- SQL Semantics Multiple-Choice Reasoning Medium Pro
- Selecting Python, Java, or C++ Across Trading Services Hard Pro
- Net Portfolio Deltas by Asset Group Medium Pro
- Optimal Multi-Symbol Trading Plan Medium Pro
- Fewest Operations to Reach Target Integer Medium Pro