KatInterview

Build a Wildcard-Aware URL Router with Literal Priority

Data Structure DesignModel answer
MediumModel answerData Structure Designtriebacktrackingrouting

Last 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.
  • captures holds 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.