KatInterview

Pattern Router for Sensor Topics with Placeholders and a Tail Wildcard

Data Structure DesignModel answer
HardModel answerData Structure Designtriebacktrackingrouting

Last 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 to name. Every other pattern segment must equal the topic segment exactly.
  • resolve returns the winning pattern and its bindings, or None if 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>.temp and plant.<zone>.temp) must raise ValueError.
  • Empty segments such as plant..temp are 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.
  • resolve is called far more often than add.

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.