KatInterview

Call Channel State Manager

Data Structure DesignModel answer
MediumModel answerData Structure Designstate-machineobject-oriented-designvalidation

Last 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:

  1. Custom Exception: Create a ConnectionException class that stores an error message string.

  2. Abstract Interface: Define CommsHandlerABC as an abstract base with three methods:

    • connect(user1: Caller, user2: Caller) -> str: Initiate a call between two users or raise ConnectionException
    • hangup(user1: Caller, user2: Caller) -> str: Terminate the call or raise ConnectionException
    • clear_all() -> None: Immediately reset all state
  3. Concrete Implementation: Build CommsHandler that 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_all always 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 Bob
  • hangup Alice Bob
  • clear_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.