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).

  1. connect(user1, user2) -> str
    • Self-call check (evaluated first, even when a call is active): if user1.name == user2.name, raise CommunicationException(f"{user1.name} cannot connect with {user2.name}").
    • Busy-channel check: otherwise, if the channel already holds an active pair (including (user1, user2) themselves), raise CommunicationException("Connection in use. Please try later").
    • Success: record {user1.name, user2.name} as the active call and return f"Connection established between {user1.name} and {user2.name}".
  2. hangup(user1, user2) -> str
    • Self-hangup check (evaluated first): if user1.name == user2.name, raise CommunicationException(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 raise CommunicationException(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".
  3. clear_all() -> None
    • Reset the channel to idle regardless of whether a call is underway, returning None.
  4. run_comms_handler(operations, arguments)
    • Replay operations sequentially against a single CommsHandler instance ("clear_all" takes [] and appends None; "connect" and "hangup" take [{"name": n1}, {"name": n2}] and append the returned string, or "EXCEPTION: " + message whenever CommunicationException is raised).

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 operations is "connect", "hangup", or "clear_all".
  • Every caller object provides a non-empty string .name attribute.
  • Each method on CommsHandler runs in O(1) time and O(1) space (treating caller name length as bounded).

Step-by-step walkthrough

  1. 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 if user1.name == user2.name, raises if the channel is already occupied, or connects the pair and returns a confirmation string.
      • hangup(user1, user2) -> raises if user1.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 returns None.
    • run_comms_handler(operations, arguments): replays a sequence of calls against one CommsHandler and records each return value (or "EXCEPTION: " + message whenever CommunicationException is raised).
  2. 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 of Caller objects? 1. Identity by name: Two Caller("Maya") instances are distinct Python objects in memory, so comparing user1 == user2 would miss self-calls unless we compare .name. 2. Order independence: Python sets ignore order, so {"Liam", "Maya"} == {"Maya", "Liam"} evaluates to True. 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}
    
  3. Define `Caller`, `CommunicationException`, and `CommsHandlerABC`

    Since our file runs standalone in the judge, we define clean, minimal versions of Caller and CommsHandlerABC alongside CommunicationException.

    Passing message to super().__init__(message) ensures str(error) returns the message as standard Python code expects, while saving self.message = message makes reading it explicit. Marking the three interface methods with @abstractmethod makes Python enforce that CommsHandler implements 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:
            pass
    
  4. Implement `connect` with validation in exact priority order

    Check the validation precedence inside connect carefully: 1. First test user1.name == user2.name and raise "{user1.name} cannot connect with {user2.name}". 2. Only when the two callers are distinct, test self.active_pair is not None and 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 call connect(Maya, Liam) a second time while already talking, their names differ and self.active_pair is occupied, so "Connection in use. Please try later" is raised naturally.

    We assign self.active_pair only 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}"
    
  5. Implement `hangup` and `clear_all`

    hangup follows the exact same defensive pattern: 1. Check user1.name == user2.name first so self-hangup always reports "{name} cannot hangup with {name}". 2. Check self._is_active_pair(user1, user2). Both names must match! If Maya and Liam are talking and someone calls hangup(Maya, Noah), {"Maya", "Noah"} != {"Maya", "Liam"}, so we raise without dropping Maya and Liam's call. 3. Set self.active_pair = None and format the disconnect string using {user1.name} first and {user2.name} second — even if hangup(Liam, Maya) reversed the original connect(Maya, Liam) order.

    clear_all simply resets self.active_pair = None whether 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 = None
    
  6. Wire up the `run_comms_handler` adapter and trace Example 2

    The judge passes parallel lists operations and arguments. For "clear_all", arguments[i] is empty [] and we append None. For "connect" and "hangup", we wrap the two input dicts in Caller objects, invoke the method inside a try block, and catch only CommunicationException (so genuine bugs like typos or KeyError are 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"}
    
  7. 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) per connect, hangup, or clear_all call, and O(M) total across the M operations. 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) inside CommsHandler because self.active_pair holds either None or a set of two strings at all times, plus O(M) in run_comms_handler to store the output list of M results.

Edge cases

  • Same user passed twice (connect(Maya, Maya) or hangup(Maya, Maya)): Raises the self-connect or self-hangup CommunicationException immediately, even when another pair is currently using the channel (Example 3).
  • Already-connected pair calls connect again (connect(Maya, Liam) or connect(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 by hangup(Liam, Maya)): Succeeds because set equality {"Liam", "Maya"} == {"Maya", "Liam"} is order-independent, while the returned string preserves the hangup argument 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_all on an already free channel: Safely leaves self.active_pair as None and returns None without raising.
  • Duck-typed caller objects: Using duck typing (reading .name directly rather than checking isinstance(user, Caller)) lets any caller object with a .name attribute work seamlessly.
  • Empty operation list ([]): Returns [] without touching the handler.

Common mistakes

  • Checking self.active_pair is not None before user1.name == user2.name: Causes connect(Noah, Noah) during an active call to raise "Connection in use. Please try later" instead of "Noah cannot connect with Noah".
  • Comparing user1 == user2 instead of user1.name == user2.name: Default object equality in Python checks object identity (is), so two separate Caller("Maya") instances appear "different" and Example 3 fails.
  • Dropping the active call when only one user in hangup matches: Checking user1.name in self.active_pair or user2.name in self.active_pair lets hangup(Maya, Noah) cut off Maya and Liam's conversation.
  • Mutating self.active_pair before all validation passes: Leaves the channel corrupted after a raised exception.
  • Using bare except Exception: in the adapter: Swallows real programming bugs (such as AttributeError or KeyError) 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): Equally O(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_pair inside _is_active_pair.
  • Define __eq__ and __hash__ on Caller by name: Allows storing frozenset({user1, user2}), though in interviews where Caller is provided externally by the test suite, you cannot modify Caller and comparing .name is safer.

Follow-up questions

  • How would you make CommsHandler safe when multiple threads invoke connect, hangup, and clear_all concurrently? Right now connect suffers from a check-then-act race condition (a concurrency bug where two threads both see self.active_pair is None at the same instant and both overwrite self.active_pair, silently dropping the first call). Add self._lock = threading.Lock() in __init__ and wrap the body of connect, hangup, and clear_all inside with self._lock: so checking and updating self.active_pair happen as one indivisible step; Python's with block automatically releases the lock even when CommunicationException is raised.
  • How would you generalize the design to allow up to K simultaneous two-party calls while keeping operations O(1)? Replace self.active_pair with a dictionary self.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 is len(self.partner_of) // 2. In connect(u1, u2), check u1 != u2, check that neither u1 nor u2 is already in self.partner_of, and check len(self.partner_of) // 2 < K before setting self.partner_of[u1] = u2 and self.partner_of[u2] = u1; hangup verifies self.partner_of.get(u1) == u2 and deletes both keys, keeping connect and hangup O(1) average time (clear_all() simply calls self.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 str return type as normal status messages, forcing every caller to parse text like "cannot connect" to tell whether a call succeeded. Raising CommunicationException separates normal control flow from error handling, and in a larger codebase you can subclass it into SameUserError(CommunicationException) and LineBusyError(CommunicationException) so callers can retry on LineBusyError while still catching all communication errors via CommunicationException.

Follow-up questions

Similar questions

More Akuna Capital interview questions

All 26 Akuna Capital questions →