Route API Gateway Requests to Handlers With Wildcard Path Segments
Last updated: November 29, 2026
Quick Overview
Implement a router with `add_route(pattern, handler)` and `match(path)`, where patterns are slash-separated segments and `*` matches exactly one segment. When several routes match, prefer the one with a literal segment at the earliest position where they differ.
Amazon
November 29, 20260
0
0 solved
Implement a router with `add_route(pattern, handler)` and `match(path)`, where patterns are slash-separated segments and `*` matches exactly one segment. When several routes match, prefer the one with a literal segment at the earliest position where they differ.
An onsite design-a-structure question in Amazon's style, modeled on how a service like API Gateway maps resource paths such as `/orders/{id}/items` to integrations. The interviewer looks for a segment-level trie, correct precedence between literal and wildcard children, and backtracking when the literal branch dead-ends.
What the Interviewer Expects
- Uses a trie keyed by path segments, not characters
- Gives literal children priority over the wildcard child
- Backtracks to the wildcard branch if the literal branch fails
- Requires a full match ending on a node with a handler
- Discusses conflicts such as registering the same pattern twice
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you capture the wildcard values as named parameters?
- How would you add a trailing `**` that matches the rest of the path?
- How would you make lookups lock-free while routes are being updated?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Patterns and paths are absolute, slash-separated; empty segments are ignored. * matches exactly one non-empty segment. Among matching routes, a literal beats * at the first differing position. Ret...
High-Level Design
Build a trie whose edges are whole segments. Each node has a dict of literal children, at most one wildcard child, and an optional handler. Matching is a DFS that tries the literal child first and fal...