KatInterview

Path Template Router with Variables and Wildcard Tails

Data Structure DesignModel answer
MediumModel answerData Structure Designtrieroutingbacktracking

Last updated

Build a trie-based URL router that registers templates with named captures and wildcard tails, resolves concrete paths with literal-first precedence and backtracking, and detects shape conflicts.

Path Template Router with Variables and Wildcard Tails

You are building the routing layer for a minimal HTTP framework. At startup, route templates are registered alongside their handlers. At request time, a concrete URL path is matched against those templates and any captured values are extracted.

Implement the following interface:

class Router:
    def add(self, template: str, handler) -> None: ...
    def match(self, path: str) -> tuple[object, dict[str, str]] | None: ...

Path normalization: split on / and drop empty segments. So /catalog/42/ becomes ["catalog", "42"] and / becomes []. Query strings are already stripped before any call reaches your router.


Part 1 — Literals and named captures

A template segment is one of:

  • A literal such as catalog — matches exactly that text.
  • A named capture written {name} — matches any single non-empty segment and records what it matched.

Rules:

  • Precedence: at any position where both a literal and a capture could advance the match, try the literal branch first.
  • Backtracking: if the literal branch fails further down the path, retry with the capture branch.
  • Conflict detection: add must raise ValueError when two templates are structurally identical — meaning they look the same after every variable name is replaced by a generic placeholder. So /catalog/{id} and /catalog/{sku} conflict because both reduce to /catalog/{?}.
r = Router()
r.add("/catalog/new",           "new")
r.add("/catalog/new/badge",     "badge")
r.add("/catalog/{sku}/reviews", "reviews")
r.add("/catalog/{sku}/reviews/{rid}", "review")

r.match("/catalog/new")               # ("new",     {})
r.match("/catalog/99/reviews")        # ("reviews", {"sku": "99"})
r.match("/catalog/new/reviews")       # ("reviews", {"sku": "new"})  ← backtracked
r.match("/catalog/5/reviews/r7")      # ("review",  {"sku": "5", "rid": "r7"})
r.match("/catalog")                   # None

Part 2 — Wildcard tail segment

Extend the router with a wildcard capture written {*name}. It:

  • May only appear as the final segment of a template; placing it anywhere else raises ValueError.
  • Matches one or more remaining segments, joining them with /.
  • Has the lowest precedence at any position: try literal first, then named capture, then wildcard.
r.add("/assets/{*path}",        "assets")
r.add("/assets/{owner}/config", "config")

r.match("/assets/img/logo.png")  # ("assets", {"path": "img/logo.png"})
r.match("/assets/ali/config")    # ("config", {"owner": "ali"})
r.match("/assets")               # None  — wildcard needs at least one segment

Registering a second wildcard on the same trie node also raises ValueError.


Constraints

  • Up to 10^5 templates may be registered.
  • Paths are at most 50 segments long.
  • A single match call must not scan every registered template linearly.
  • State the time complexity of both add and match.

Hints

Hint 1

Think about what determines whether two routes conflict. If you erase every variable name and leave only the segment *type* (literal vs. capture vs. wildcard), the structural path through the trie is what matters — two routes conflict when they trace the exact same path through that structure.

Hint 2

For precedence and backtracking, the order in which you try children at each node is all you need: literals first, then the capture child, then the wildcard. A plain recursive DFS over those ordered alternatives gives you both precedence and backtracking for free.

Hint 3

Worst-case backtracking can visit O(2^d) nodes for a path of depth d. Think about what information would let you skip a subtree you've already determined cannot produce a match, and why that memoization is safe regardless of what was captured so far.