Build a Slash-Command Router with Literal and Wildcard Segments
Data Structure DesignModel answerLast 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, orNoneif 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.
:envcaptures"staging"from the command tokenstaging.
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
resolvecalls. - A single
resolvemust not scan every registered pattern — it should scale with command length, not pattern count. tokenizeis 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to model registered patterns as a trie keyed by segment, not as a flat list of strings. Each trie node stores:
children: a dict mapping literal segment text to a child node.param_child: at most one child node for parameter segments.param_name: the capture name associated withparam_child(e.g."env").handler: set only when this node is the terminal node of a registered pattern.
register walks the trie top-down, creating nodes on the fly. resolve tokenizes the command once, then advances one node per token. The result is an O(k) lookup for a command with k segments — completely independent of how many patterns are registered.
Design Decisions
Precedence — literals beat parameters. When a token matches both a literal child and the parameter child at the same node, the literal child wins. This mirrors how Express and Gin-style HTTP routers behave: if you registered an exact route, you presumably want it to take priority. It also keeps the algorithm deterministic with no need to inspect multiple branches.
No backtracking. Once the router descends into a literal child, it stays there. If that branch has no continuation for the remaining tokens, resolve returns None — it does not retry the parameter branch. This is why resolve("env/staging/restart") returns None in the example: the router commits to the staging literal node (which exists because env/staging/logs was registered) and never considers env/:env/restart. This is the core trade-off:
- Pro: guaranteed
O(segments)lookups, simple mental model, predictable behavior. - Con: a command can return
Noneeven though a parameterized route would technically match it, which surprises users who expect greedy fallback.
A backtracking router would find env/:env/restart in that case, but at the cost of potentially O(2^k) paths in degenerate tries. For a chat-ops bot with bounded segment counts, backtracking is feasible, but you'd want to document the behavior explicitly and cap recursion depth.
Implementation
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Callable, Optional
Handler = Callable[..., object]
def tokenize(command: str) -> list[str]:
return [seg for seg in command.strip('/').split('/') if seg]
@dataclass
class _Node:
children: dict[str, _Node] = field(default_factory=dict)
param_name: Optional[str] = None
param_child: Optional[_Node] = None
handler: Optional[Handler] = None
class CommandRouter:
def __init__(self) -> None:
self._root = _Node()
def register(self, pattern: str, handler: Handler) -> None:
node = self._root
for seg in tokenize(pattern):
if seg.startswith(':'):
name = seg[1:]
if node.param_child is None:
node.param_child = _Node()
# Reject conflicting param names at the same trie position
if node.param_child.param_name not in (None, name):
raise ValueError(
f"Conflicting parameter names at position: "
f"{node.param_child.param_name!r} vs {name!r}"
)
node.param_child.param_name = name
node = node.param_child
else:
node = node.children.setdefault(seg, _Node())
if node.handler is not None:
raise ValueError(f"Pattern already registered: {pattern!r}")
node.handler = handler
def resolve(self, command: str) -> tuple[Handler, dict[str, str]] | None:
node = self._root
params: dict[str, str] = {}
for seg in tokenize(command):
if seg in node.children:
# Literal match wins
node = node.children[seg]
elif node.param_child is not None:
# Fall through to parameter match
params[node.param_child.param_name] = seg
node = node.param_child
else:
return None
if node.handler is None:
return None
return node.handler, params
Edge Cases Worth Testing
- Empty command — matches a zero-segment pattern if one was registered; otherwise
None. - Prefix without handler —
env/stagingshould returnNoneeven ifenv/staging/logsexists; the walk ends at a node with no handler. - Duplicate registration — registering the same literal pattern twice should raise, not silently overwrite.
- Conflicting parameter names —
env/:env/statusandenv/:region/statusshare a trie node for the second segment; this should be rejected (or explicitly aliased) at registration time. - Command longer than any pattern — the walk will hit a node with no children and no param child for the extra token, returning
Nonecorrectly. - Single-segment commands — work the same way; the root node's children handle them directly.
Complexity
| Operation | Time | Space |
|---|---|---|
register | O(k) per pattern | O(total segments across all patterns) |
resolve | O(k) per command | O(k) for the captured params dict |
where k is the number of segments in the pattern or command. The trie structure means resolve never looks at unrelated branches — it's a straight-line walk regardless of how many patterns are registered.