KatInterview

Build a Slash-Command Router with Literal and Wildcard Segments

Data Structure DesignModel answer
MediumModel answerData Structure Designtrieroutingdesign

Last updated

Implement a trie-based router that matches tokenized bot commands to registered handlers, resolving conflicts between exact and parameterized path segments.

Slash-Command Router

Your team is building an internal bot that listens in a shared chat channel. Users trigger actions by typing structured commands like /env staging rollback or /service payments logs. Your job is to write the routing layer that connects each incoming command to the function that handles it.

Commands and patterns are both represented as slash-separated strings. You need to support two operations on a CommandRouter class:

  • register(pattern, handler) — stores a handler for a given pattern.
  • resolve(command) — given a concrete command, returns the matching handler and a dictionary of any captured argument values, or None if nothing matches.

Patterns support two kinds of segments:

  • Literal segments — plain words that must match exactly, e.g. rollback.
  • Parameter segments — prefixed with a colon, match any single token and capture it under the given name, e.g. :env captures "staging" from the command token staging.

A helper is provided — do not rewrite it:

def tokenize(command: str) -> list[str]:
    """'env/staging/rollback' -> ['env', 'staging', 'rollback']"""

Starting interface (adjust as needed after stating your design decisions):

from typing import Callable

Handler = Callable[..., object]

class CommandRouter:
    def register(self, pattern: str, handler: Handler) -> None: ...
    def resolve(self, command: str) -> tuple[Handler, dict[str, str]] | None: ...

Example

register("ping", ping_handler)
register("env/staging/rollback", rollback_staging_handler)
register("env/:env/rollback", rollback_any_handler)
register("env/staging/logs", logs_staging_handler)
register("env/:env/restart", restart_any_handler)

resolve("ping")                   -> (ping_handler, {})
resolve("env/staging/rollback")   -> (rollback_staging_handler, {})
resolve("env/prod/rollback")      -> (rollback_any_handler, {"env": "prod"})
resolve("env/staging/restart")    -> ???
resolve("env/prod/restart")       -> (restart_any_handler, {"env": "prod"})

Constraints

  • Up to 10,000 patterns may be registered, each up to 20 segments long, with up to 10^5 resolve calls.
  • A single resolve must not scan every registered pattern — it should scale with command length, not pattern count.
  • tokenize is already implemented; do not write your own.

You must decide and defend

Precedence: when the same position in a command could match either a literal segment or a parameter segment (e.g. staging against both staging and :env), which takes priority?

Backtracking: if the router follows a literal branch that turns out to have no handler or continuation for the remaining tokens — like env/staging/restart above, where env/staging/logs exists but not env/staging/restart — does it fall back to the parameter branch, or return None? Pick one, implement it, and be ready to explain the trade-off.

Hints

Hint 1

Think about the data structure that lets you walk one segment at a time without scanning every registered pattern — a prefix tree keyed by segment text fits naturally here.

Hint 2

At each trie node you need to store two kinds of outgoing edges: a dictionary for literal children, and at most one special child for parameter segments. What information does the parameter child need to carry?

Hint 3

The backtracking question is the crux: a no-backtrack policy gives you a clean O(segments) lookup and a simple mental model, but it can miss a valid parameterized route when a literal branch dead-ends. Make sure you can describe this trade-off clearly, with a concrete example.