Call Channel State Manager
Data Structure DesignModel answerLast updated
Build a stateful manager that allows exactly one active two-party call at a time, with proper validation and error handling.
You need to build a manager for a call channel that supports exactly one active conversation between two parties at any moment.
Your implementation must include:
-
Custom Exception: Create a
ConnectionExceptionclass that stores an error message string. -
Abstract Interface: Define
CommsHandlerABCas an abstract base with three methods:connect(user1: Caller, user2: Caller) -> str: Initiate a call between two users or raiseConnectionExceptionhangup(user1: Caller, user2: Caller) -> str: Terminate the call or raiseConnectionExceptionclear_all() -> None: Immediately reset all state
-
Concrete Implementation: Build
CommsHandlerthat maintains the current call state and enforces these rules:- Only one call can be active at any time
- A user cannot call themselves
- New connection attempts while a call is active must fail
- Hangup only succeeds for the currently connected pair (in either order)
clear_allalways succeeds and resets state
The Caller object has a name: str attribute that uniquely identifies each user.
Input Format: Commands separated by semicolons or newlines:
connect Alice Bobhangup Alice Bobclear_all
Output Format: Prefix each result with Success: or Error: based on whether the operation succeeded or raised an exception.
Example:
Input:
connect Alice Bob; connect Carol Dave; hangup Alice Bob; connect Carol Dave; hangup Carol Dave; connect Eve Eve; hangup Alice Bob
Output:
Success: Connection established between Alice and Bob
Error: Connection in use. Please try later
Success: Alice and Bob are disconnected
Success: Connection established between Carol and Dave
Success: Carol and Dave are disconnected
Error: Eve cannot connect with Eve
Error: Alice and Bob not found in the communication channel
Hints
Hint 1
Model the handler as a state machine with two states: idle (no call) and busy (one active pair).
Hint 2
Store the active pair as an unordered set so that hangup works regardless of argument order.
Hint 3
Validate inputs (like self-connections) before checking the state to provide more specific error messages.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires building a state machine to manage a single two-party call channel. The handler has two states:
- Idle: No active call exists
- Busy: Exactly one pair is connected
Core Design Decisions
State Representation: Use a single field self.active that is either None (idle) or a frozenset containing the two caller names (busy). Using an unordered set ensures hangup(Alice, Bob) matches a call started with connect(Bob, Alice).
Operation Flow: Each operation follows this pattern:
- Validate inputs (e.g., check for self-connections)
- Check current state compatibility
- Either update state and return success message, or raise
ConnectionExceptionwith the specific error
Separation of Concerns: The handler returns plain result messages. The driver wraps them with Success: or catches exceptions and wraps with Error:. This keeps formatting logic out of business logic.
State Transitions
| Operation | Condition | Action |
|---|---|---|
connect(a, b) | a == b | Raise error: cannot connect with self |
connect(a, b) | Channel busy | Raise error: channel in use |
connect(a, b) | Channel idle, a ≠ b | Set active pair, return success |
hangup(a, b) | a == b | Raise error: cannot hangup with self |
hangup(a, b) | Active pair is {a, b} | Clear active pair, return success |
hangup(a, b) | Otherwise | Raise error: pair not found |
clear_all() | Any state | Reset to idle |
Why This Works
Single Call Guarantee: connect only succeeds when active is None. This is the only way to set active, so two concurrent calls are impossible.
Self-Connection Prevention: Comparing user1.name == user2.name before state checks provides immediate validation.
Unordered Pair Matching: Storing as frozenset means both hangup(Alice, Bob) and hangup(Bob, Alice) will match a call between Alice and Bob.
Robust Error Handling: Each invalid operation has a specific error message. The validation order (input validation before state checks) provides more informative errors.
Walkthrough of Example
connect Alice Bob: Idle → Busy with {Alice, Bob}connect Carol Dave: Busy → Error (channel occupied)hangup Alice Bob: Busy with {Alice, Bob} → Idleconnect Carol Dave: Idle → Busy with {Carol, Dave}hangup Carol Dave: Busy with {Carol, Dave} → Idleconnect Eve Eve: Self-connection → Errorhangup Alice Bob: Idle (no active call) → Error (pair not found)
Edge Cases
- Reversed hangup order:
hangup(Bob, Alice)works whenconnect(Alice, Bob)was called - Partial match:
hangup(Alice, Carol)during Alice-Bob call fails (both users must match) - Double hangup: Second attempt fails with "not found"
- Clear on idle channel:
clear_all()is idempotent and always succeeds - Message formatting: Uses argument order as provided (e.g., "Bob and Alice are disconnected" if called that way)
Complexity
- Time: O(1) per operation (constant comparisons on two-element set)
- Space: O(1) for handler state
Implementation
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import FrozenSet, Optional
class ConnectionException(Exception):
def __init__(self, message: str):
super().__init__(message)
self.message = message
def __str__(self) -> str:
return self.message
@dataclass(frozen=True)
class Caller:
name: str
class CommsHandlerABC(ABC):
@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):
self.active: Optional[FrozenSet[str]] = None
def connect(self, user1: Caller, user2: Caller) -> str:
if user1.name == user2.name:
raise ConnectionException(
f"{user1.name} cannot connect with {user2.name}"
)
if self.active is not None:
raise ConnectionException("Connection in use. Please try later")
self.active = frozenset((user1.name, user2.name))
return f"Connection established between {user1.name} and {user2.name}"
def hangup(self, user1: Caller, user2: Caller) -> str:
if user1.name == user2.name:
raise ConnectionException(
f"{user1.name} cannot hangup with {user2.name}"
)
if self.active == frozenset((user1.name, user2.name)):
self.active = None
return f"{user1.name} and {user2.name} are disconnected"
raise ConnectionException(
f"{user1.name} and {user2.name} not found in the communication channel"
)
def clear_all(self) -> None:
self.active = None
# Driver code
def process_commands(lines):
handler = CommsHandler()
results = []
for line in lines:
parts = line.split()
if not parts:
continue
command = parts[0].lower()
try:
if command == "clear_all":
handler.clear_all()
elif command in ("connect", "hangup") and len(parts) == 3:
u1, u2 = Caller(parts[1]), Caller(parts[2])
msg = handler.connect(u1, u2) if command == "connect" else handler.hangup(u1, u2)
results.append(f"Success: {msg}")
except ConnectionException as e:
results.append(f"Error: {e}")
return results
Common Mistakes
- Storing active users in separate variables instead of as a pair, making order matching difficult
- Forgetting to make the pair unordered (using tuple instead of frozenset)
- Checking state before validating inputs, giving less helpful errors
- Putting formatting logic inside the handler methods instead of the driver
- Not implementing the abstract base class correctly
- Hardcoding error messages instead of using the exception's message attribute