Path Template Router with Variables and Wildcard Tails
Data Structure DesignModel answerLast 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:
addmust raiseValueErrorwhen 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
matchcall must not scan every registered template linearly. - State the time complexity of both
addandmatch.
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: segment trie with ordered DFS
Data structure
Build a trie where each node represents one position in a path template. Every node holds:
literals: dict[str, Node]— one child per distinct literal segment seen at this position.var: Node | None— a single shared child for all{name}captures at this position. Because two templates that differ only in their variable names are considered conflicts, they must share this child. The variable name itself is not stored on the node.tail— stores(handler, names)when a{*name}wildcard ends at this node.handler— stores(handler, names)when a full template ends exactly here.
Variable names are collected into a list as you walk the trie during add, and stored only at the terminal node (the handler or tail slot). During match, captured values are collected positionally and zipped with that list at the very end. This design means the trie's shape encodes the route structure, and names are just metadata on the leaves.
Conflict detection
Conflicts fall out naturally. Two templates share the same shape when every step through the trie lands on the same node: literal segments hit the same literals child, and any {x} or {y} both advance through var. If add tries to assign a handler or tail that is already occupied, that is a conflict → raise ValueError.
Match: depth-first search with ordered alternatives
At each node and index i into the split path, try in order:
literals[segs[i]]if it exists.node.varif it exists (capturessegs[i]).node.tailif it exists and there is at least one segment left (captures"/".join(segs[i:])).
Return the first branch that leads to a complete match. Because we try these in order and recurse before falling through, literal-first precedence and backtracking are both handled by the recursion with no extra bookkeeping.
Memoizing failures
In the worst case (alternating literal/variable siblings all the way down), the DFS could visit O(2^d) nodes for a path of depth d. With d ≤ 50 this is unacceptable. The fix: track (id(node), i) pairs that are known to lead nowhere. When backtracking reaches a pair it has already failed, skip it immediately.
This is safe because whether a subtree can complete a match depends only on the remaining path segments segs[i:], not on what was captured so far. Captures affect the result, not the reachability. So a failed (node, depth) pair fails for every caller.
Complexity
add: O(k) where k is the number of segments in the template.match: O(d) typical, O(nodes × d) worst case with memoization, where d ≤ 50.- Space: O(total segments across all templates).
Implementation
from typing import Optional
def _split(path: str) -> list[str]:
return [s for s in path.split("/") if s]
class _Node:
__slots__ = ("literals", "var", "handler", "tail")
def __init__(self):
self.literals: dict[str, "_Node"] = {}
self.var: Optional["_Node"] = None
self.handler = None # (handler, [name, ...]) when a route ends here
self.tail = None # (handler, [name, ...]) for a {*name} ending here
class Router:
def __init__(self):
self.root = _Node()
def add(self, template: str, handler) -> None:
segs = _split(template)
node = self.root
names: list[str] = []
for i, seg in enumerate(segs):
if seg.startswith("{*") and seg.endswith("}"):
if i != len(segs) - 1:
raise ValueError(f"wildcard must be the last segment: {template}")
if node.tail is not None:
raise ValueError(f"conflicting route: {template}")
node.tail = (handler, names + [seg[2:-1]])
return
if seg.startswith("{") and seg.endswith("}"):
names.append(seg[1:-1])
if node.var is None:
node.var = _Node()
node = node.var
else:
if seg not in node.literals:
node.literals[seg] = _Node()
node = node.literals[seg]
if node.handler is not None:
raise ValueError(f"conflicting route: {template}")
node.handler = (handler, names)
def match(self, path: str) -> tuple | None:
segs = _split(path)
failed: set[tuple] = set() # (id(node), depth) known dead ends
def dfs(node: _Node, i: int, captured: list[str]):
if i == len(segs):
if node.handler is None:
return None
return node.handler, captured
key = (id(node), i)
if key in failed:
return None
seg = segs[i]
# 1. try literal
child = node.literals.get(seg)
if child is not None:
res = dfs(child, i + 1, captured)
if res is not None:
return res
# 2. try named capture
if node.var is not None:
res = dfs(node.var, i + 1, captured + [seg])
if res is not None:
return res
# 3. try wildcard tail (needs at least one segment, already guaranteed by i < len)
if node.tail is not None:
return node.tail, captured + ["/".join(segs[i:])]
failed.add(key)
return None
found = dfs(self.root, 0, [])
if found is None:
return None
(handler, names), values = found
return handler, dict(zip(names, values))
Edge cases to call out
- Root path
/: splits to[], so its handler lives on the root node itself. Make suredfschecksnode.handlerwheni == len(segs)even at depth zero. - Trailing slashes: dropped by the split, so
/catalog/newand/catalog/new/resolve identically. If the framework needs to distinguish them, the normalization step is the right place to handle it, not the trie. - Percent-encoded slashes: decode after splitting so that
%2Fin a segment is treated as a literal character, not a path separator. - Catch-all with zero segments:
/assetssplits to["assets"]; the wildcard node underassetsis never reached, so it correctly returnsNone.
Common mistakes
- Storing variable names on intermediate nodes rather than terminals — this breaks coexistence of
/a/{x}/band/a/{y}/csince they share the samevarchild. - Forgetting to backtrack after a literal match fails deeper in the tree — the
/catalog/new/reviewscase catches this. - Memoizing successful results instead of (or in addition to) failures — success memoization is wrong because the same
(node, depth)can yield different captures depending on the path taken to get there. - Allowing the wildcard to match zero segments — re-read the requirement:
{*name}needs at least one segment remaining.
Alternatives worth mentioning
A linear scan with one compiled regex per template is the simplest possible implementation, but it is O(routes) per request and precedence depends on registration order. Production routers like Go's httprouter use a radix tree (compressed trie) that merges single-child chains to save memory and pointer hops, and they often ban ambiguous literal/variable siblings outright to avoid backtracking entirely.