Build a Wildcard-Aware URL Router with Literal Priority
Data Structure DesignModel answerLast updated
Design a router that stores path templates with {name} wildcards and resolves concrete paths to a handler plus captured values, preferring exact segments and backtracking when they dead-end.
You are building the routing layer for a content delivery service. Handlers for different kinds of assets (originals, thumbnails, and so on) are attached to route templates such as /images/{assetId}/thumbnail or /images/featured/thumbnail. In a template, a segment wrapped in braces, like {name}, is a wildcard that matches exactly one segment of a request path. All other segments are literals and must match character for character.
Implement this class:
class AssetPathResolver:
def register(self, pattern: str, handler) -> None: ...
def resolve(self, path: str) -> tuple[object, dict[str, str]] | None: ...
register(pattern, handler) stores a template together with its handler. It must raise an error immediately, and not overwrite anything, when:
- the same template is registered a second time, or
- the new template cannot be told apart from an existing one, for example because the two differ only in the name of a wildcard at the same position (
/cdn/{a}/{b}after/cdn/{bucket}/{key}).
resolve(path) takes a concrete path (it never contains wildcards). It returns (handler, captures), where captures maps each wildcard name in the winning template to the segment it matched. It returns None if no template fits.
Rules
- A path matches only templates with exactly the same number of segments.
- When a segment could go either to a literal route or to a wildcard route, try the literal first. If that choice leads to a dead end later in the path, backtrack and try the wildcard at that position.
capturesholds only the wildcards of the template that actually matched.- Leading, trailing and repeated slashes should not change the outcome.
Examples
register("/images/{assetId}/thumbnail", thumb_handler)
register("/images/featured/thumbnail", featured_handler)
register("/images/{assetId}/full", full_handler)
resolve("/images/featured/thumbnail") -> (featured_handler, {})
resolve("/images/42/thumbnail") -> (thumb_handler, {"assetId": "42"})
resolve("/images/42/full") -> (full_handler, {"assetId": "42"})
resolve("/images/42/nope") -> None
register("/cdn/static/logo.png", logo_handler)
register("/cdn/{bucket}/{key}", generic_handler)
resolve("/cdn/static/other.png")
-> (generic_handler, {"bucket": "static", "key": "other.png"})
In the second example the literal static branch is tried first, fails at other.png, and the resolver falls back to the wildcard branch.
State the time and space complexity of register and resolve, and be precise about the worst case for resolve.
Hints
Hint 1
Scanning every registered template for each request is slow and makes literal-over-wildcard priority awkward. Think about a structure that shares common prefixes segment by segment.
Hint 2
In a prefix tree keyed by segments, each node needs two kinds of outgoing edges: a map of exact-text children and one wildcard child. Decide what to do when two templates use different wildcard names at the same spot.
Hint 3
Resolve recursively: at each node try the literal child first and return only if it produces a full match, otherwise try the wildcard child with the capture added. Think about how many branches can be explored in the worst case, and whether it is really linear.
Hint 4
Remember that a node can be an intermediate step toward longer templates without having a handler itself. Reaching the last segment is not enough; the node must terminate a registered template.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a segment-level trie (prefix tree). Split each template on /, ignore empty pieces (this handles leading, trailing and doubled slashes), and let each trie level represent one segment position.
Each node stores:
literals: a dict from exact segment text to child node.wild_child: at most one child reached via any wildcard segment, pluswild_name, the capture name used on that edge.handlerandpattern: set only if some registered template ends at this node.
Only one wildcard child is kept per node because two wildcard edges leaving the same node would match exactly the same set of inputs, so they would be indistinguishable.
Registration
Walk the template's segments from the root:
- For a literal segment, move to (or create) the matching literal child.
- For a wildcard segment
{name}, create the wildcard child if it does not exist yet and remembername. If it already exists with a different name, raise an error. Otherwise the capture key at that position would be ambiguous, and the two templates would be the same shape. - After the last segment, if the node already has a handler, raise (exact duplicate). Otherwise store the handler.
This is stricter than strictly necessary: two templates that share a prefix and use different wildcard names at the same position are rejected even if their suffixes differ. It keeps each node's capture name unambiguous and the structure simple. A more permissive design would store capture names per terminal template and compare shapes only.
Resolution
Resolve with a depth-first search that carries the segment index and the captures collected so far:
- If all segments are consumed, return the node's handler and the captures when the node has a handler, else fail.
- If a literal child exists for the current segment, recurse into it. If it returns a match, return that.
- Otherwise, or if the literal branch failed, recurse into the wildcard child with
captures + {wild_name: segment}. - If neither works, return
None.
The "try literal, return if success, else try wildcard" structure at every level gives the priority rule and the backtracking in one place. A literal branch can fail many levels below, and control simply returns to the nearest ancestor that still has an untried wildcard option.
class RouteConflict(Exception):
pass
class _Node:
__slots__ = ("literals", "wild_child", "wild_name", "handler", "pattern")
def __init__(self):
self.literals = {}
self.wild_child = None
self.wild_name = None
self.handler = None
self.pattern = None
def _split(path):
return [p for p in path.split("/") if p]
def _is_wild(seg):
return len(seg) >= 2 and seg[0] == "{" and seg[-1] == "}"
class AssetPathResolver:
def __init__(self):
self._root = _Node()
def register(self, pattern, handler):
node = self._root
for seg in _split(pattern):
if _is_wild(seg):
name = seg[1:-1]
if node.wild_child is None:
node.wild_child = _Node()
node.wild_name = name
elif node.wild_name != name:
raise RouteConflict(
f"{pattern!r}: wildcard {{{name}}} clashes with "
f"{{{node.wild_name}}} at the same position"
)
node = node.wild_child
else:
node = node.literals.setdefault(seg, _Node())
if node.handler is not None:
raise RouteConflict(f"{pattern!r} duplicates {node.pattern!r}")
node.handler = handler
node.pattern = pattern
def resolve(self, path):
segs = _split(path)
def dfs(node, i, caps):
if i == len(segs):
if node.handler is None:
return None
return node.handler, caps
seg = segs[i]
child = node.literals.get(seg)
if child is not None:
found = dfs(child, i + 1, caps)
if found is not None:
return found
if node.wild_child is not None:
found = dfs(node.wild_child, i + 1,
{**caps, node.wild_name: seg})
if found is not None:
return found
return None
return dfs(self._root, 0, {})
Edge cases worth testing
- Deep dead end: with
/cdn/static/logo.pngand/cdn/{bucket}/{key}, the path/cdn/static/other.pnggoes down the literalstaticbranch, fails atother.png, and must fall back to the wildcard at thestaticlevel. - Prefix without terminal:
/images/featuredmust not match just because/images/featured/thumbnailexists. Check that the node actually has a handler. - Length mismatch: a path with more or fewer segments than any template returns
None. - Duplicates: the same template twice, and
/cdn/{a}/{b}after/cdn/{bucket}/{key}, both raise. - Slashes:
/images/42/thumbnail/andimages//42/thumbnailresolve like the clean form. - Captures: only wildcards on the matched route appear. Captures from abandoned branches never leak, because the dict is copied rather than mutated.
Complexity
register: O(k) time for a template with k segments (hash lookups per segment), and at most O(k) new nodes.resolve, typical case: close to O(k), since most paths follow one branch.resolve, worst case: each level may explore both a literal and a wildcard child, so the search can branch up to 2^k ways. It is bounded by the number of trie nodes, so it is O(min(2^k, N)) where N is the total node count. For example, registering every literal/wildcard combination of depth k and then requesting a path that fails at the last segment forces the whole trie to be visited. Because the trie is a tree, states are never revisited, so memoization does not help. In real route tables the branching is tiny, so this is acceptable, but it should be stated honestly rather than claimed as O(k).- Space: O(total segments across all templates) for the trie, since prefixes are shared, plus O(k) recursion depth and O(w) per captures dict, where w is the number of wildcards.
Common mistakes
- Returning the first literal match without backtracking, which breaks the
static/other.pngcase. - Allowing two wildcard children per node, or silently accepting differently named wildcards, so the capture key depends on registration order.
- Mutating a shared captures dict, which leaks values from failed branches.
- Treating any reached node as a match instead of requiring a handler.
- Forgetting to normalize slashes consistently in
registerandresolve. - Claiming strict O(k) resolve time while backtracking is allowed.