Pattern Router for Sensor Topics with Placeholders and a Tail Wildcard
Data Structure DesignModel answerLast updated
Design a router that maps dot-separated topics to registered patterns with named placeholders and a trailing "**", using strict left-to-right precedence and backtracking.
A factory publishes sensor readings on an internal message bus. Each message has a topic, a string of dot-separated segments such as plant.l7.temp or plant.north.motor.m3. Services subscribe by registering patterns, and for every incoming topic the bus must pick exactly one pattern to deliver it to.
Part 1: Literals and named placeholders
Implement:
class TopicRouter:
def add(self, pattern: str) -> None: ...
def resolve(self, topic: str) -> tuple[str, dict[str, str]] | None: ...
Rules:
- A pattern segment of the form
<name>is a placeholder. It matches exactly one topic segment and binds it toname. Every other pattern segment must equal the topic segment exactly. resolvereturns the winning pattern and its bindings, orNoneif no pattern matches.- Precedence: when several patterns match, compare them segment by segment from the left. At the first position where they differ, the literal beats the placeholder.
- Adding an identical pattern a second time does nothing.
- Adding a pattern that differs from an existing one only in placeholder names (for example
plant.<line>.tempandplant.<zone>.temp) must raiseValueError. - Empty segments such as
plant..tempare invalid.
add("plant.<line>.temp")
add("plant.north.temp")
add("plant.<line>.motor.<id>")
add("plant.north.motor.idle")
resolve("plant.l7.temp") -> ("plant.<line>.temp", {"line": "l7"})
resolve("plant.north.temp") -> ("plant.north.temp", {})
resolve("plant.north.motor.m3") -> ("plant.<line>.motor.<id>", {"line": "north", "id": "m3"})
resolve("plant.l7.vibration") -> None
In the third example, the literal branch north is explored first but fails at m3, so the router has to back up and try the placeholder branch.
Part 2: Tail wildcard
A pattern may end with the segment **, which may only appear last. It matches one or more remaining topic segments and binds them, joined by dots, under the key "**". At any position its precedence is the lowest: literal first, then placeholder, then **.
add("plant.**")
add("plant.<line>.motor.**")
resolve("plant.l7.vibration") -> ("plant.**", {"**": "l7.vibration"})
resolve("plant.l2.motor.coil.temp") -> ("plant.<line>.motor.**", {"line": "l2", "**": "coil.temp"})
resolve("plant.l2.motor.m1") -> ("plant.<line>.motor.<id>", {"line": "l2", "id": "m1"})
resolve("plant") -> None
Part 3: Analysis
Give the time and space complexity of add and resolve. Explain why resolve cannot degrade into exponential work caused by repeated re-exploration on a fixed set of patterns.
Constraints
- Up to 10^5 patterns, at most 32 segments per topic, each segment at most 64 characters.
resolveis called far more often thanadd.
Hints
Hint 1
Store patterns in a trie keyed by segment. Give each node a map for literal children and one single slot for the placeholder child, since placeholder names do not affect matching.
Hint 2
Precedence is just search order: at each node try the literal child, then the placeholder child, then the tail wildcard. Return the first success, which requires a depth-first search that backs up on dead ends.
Hint 3
Detect name-only conflicts by noticing that two such patterns land on the same trie node but have different pattern strings. Compute bindings after the search by walking the winning pattern alongside the topic.
Hint 4
For the complexity argument, note that the search state is fully described by the trie node, because the topic index equals the node's depth. A node is therefore reached through only one route and visited at most once.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a trie over segments. Each node holds:
literal: dict from segment text to child node.param: one child node shared by all placeholders at that depth. Placeholder names do not influence matching, so<line>and<zone>follow the same edge.exact: the pattern string that ends at this node, if any.tail: the pattern whose remaining part is**at this node, if any.
add
- Split on
.and reject empty segments. - Reject
**anywhere except the last position. - Walk from the root. For a placeholder segment, take or create the
paramchild. Otherwise take or create theliteralchild. If the last segment is**, stop before it and use thetailslot. Otherwise use theexactslot. - If the slot is empty, store the pattern. If it holds the identical string, do nothing. If it holds a different string, the two patterns share the same shape and differ only in placeholder names, so raise
ValueError.
A segment like <> has no name, so it is treated as an ordinary literal. A placeholder needs at least one character between the brackets.
resolve
Run a depth-first search walk(node, i) over the topic segments:
- If
iequals the number of segments, returnnode.exact, which may beNone. - Try
node.literal[segments[i]]. If the recursive call finds a pattern, return it. - Otherwise try
node.param. Return its result if it succeeds. - Otherwise return
node.tail. Here at least one segment remains, so the "one or more" rule of**holds automatically.
This order gives exactly the required precedence. Two competing patterns diverge at some first position, and the search explores the higher-priority branch there first. Backtracking is what makes plant.north.motor.m3 work: the north branch dead-ends and the search falls back to the placeholder branch.
Bindings are produced afterward by walking the winning pattern and the topic together. A <name> segment binds name to the topic segment at the same index. A ** binds "**" to the remaining segments joined by dots.
Code
class _Node:
__slots__ = ("literal", "param", "exact", "tail")
def __init__(self):
self.literal = {}
self.param = None
self.exact = None
self.tail = None
def _is_placeholder(seg):
return len(seg) > 2 and seg[0] == "<" and seg[-1] == ">"
def _segments(text):
parts = text.split(".")
if "" in parts:
raise ValueError(f"empty segment in {text!r}")
return parts
class TopicRouter:
def __init__(self):
self._root = _Node()
def add(self, pattern):
parts = _segments(pattern)
if "**" in parts[:-1]:
raise ValueError("'**' must be the last segment")
is_tail = parts[-1] == "**"
body = parts[:-1] if is_tail else parts
node = self._root
for seg in body:
if _is_placeholder(seg):
if node.param is None:
node.param = _Node()
node = node.param
else:
node = node.literal.setdefault(seg, _Node())
attr = "tail" if is_tail else "exact"
current = getattr(node, attr)
if current is not None and current != pattern:
raise ValueError(f"{pattern!r} clashes with {current!r}")
setattr(node, attr, pattern)
def resolve(self, topic):
segs = _segments(topic)
pattern = self._walk(self._root, segs, 0)
if pattern is None:
return None
return pattern, self._bindings(pattern, segs)
def _walk(self, node, segs, i):
if i == len(segs):
return node.exact
nxt = node.literal.get(segs[i])
if nxt is not None:
found = self._walk(nxt, segs, i + 1)
if found is not None:
return found
if node.param is not None:
found = self._walk(node.param, segs, i + 1)
if found is not None:
return found
return node.tail
@staticmethod
def _bindings(pattern, segs):
out = {}
for i, p in enumerate(pattern.split(".")):
if p == "**":
out["**"] = ".".join(segs[i:])
elif _is_placeholder(p):
out[p[1:-1]] = segs[i]
return out
Complexity
- add: O(L) hash operations for L segments, plus O(total characters) for splitting and hashing, so at most about 32 x 64 characters of work.
- Space: O(total segments over all patterns) in the worst case. Shared prefixes are stored once, so a realistic route table is much smaller. For 10^5 patterns of 32 segments this is at most 3.2 million nodes.
- resolve: The search state is just the trie node, because the topic index always equals the node's depth. Each node has exactly one path from the root, so it is visited at most once. Total work is therefore bounded by the number of nodes the search can reach, and there is no repeated re-exploration of the same subproblem, which is what causes exponential blow-up in naive regex-style matchers. Branching is at most 2 per level (literal and placeholder), so the visited nodes number at most min(V, 2^L), where V is the trie size. In practice, one branch usually succeeds quickly and lookup is close to O(L). Recursion depth is at most 32.
Edge cases and common mistakes
- Greedy matching without backtracking: committing to the literal child when it later dead-ends gives wrong answers (
Noneinstead of the placeholder match). - Applying
**to zero segments, so thatplantwrongly matchesplant.**. The tail is only reachable when at least one segment remains. - Keying the placeholder child by name. This breaks the sharing of branches and hides the name-only conflict.
- Allowing
**in the middle of a pattern, which would need much more complex matching. Reject it at registration. - Comparing precedence over the whole pattern rather than at the first differing position.
- Forgetting to validate topics for empty segments in
resolve.
Trade-offs and extensions
- Since reads dominate, make registrations copy-on-write: build a new trie, then swap the root reference atomically so readers never need locks.
- If lookups for the same hot topics repeat, add an LRU cache keyed by topic and invalidate it on registration.
- To avoid recursion or per-call allocations in a hot path, convert the search to an explicit stack, or precompute and flatten the trie into arrays.
- To report all matches, not only the best one, continue the search instead of returning on the first hit.