Google questions

URL Request Router

GoogleMedium

A web server picks a handler for each request by matching the request's URL against registered patterns. Implement this matching in a Router class.

Part 1: Match URLs to patterns

Implement a Router class with two methods:

  • add_handler(pattern) registers pattern. Registering a pattern that is already registered changes nothing.
  • get_handler(url) returns the registered pattern that matches url, or None if no registered pattern matches.

A pattern or URL starts with / and splits on / into segments. In a pattern, a segment written as {name} is a placeholder that matches any one non-empty segment. Any other segment is literal and must match exactly, with upper and lower case treated as different. A pattern matches a URL only when both have the same number of segments and every segment matches.

When several registered patterns match, take the one that is literal at the first segment where they differ, reading from the left. For example, with /a/{x}/{z} and /{y}/b/c registered, /a/b/c goes to /a/{x}/{z} because its first segment is literal while the other's is a placeholder.

A URL may contain an empty segment, as in /users//photo; no placeholder matches an empty segment.

  1. Example 1
    init
    []
    operations
    [["add_handler",["/users/{userId}/photo/{photoId}"]],["add_handler",["/users/delete"]],["get_handler",["/users/42/photo/7"]],["get_handler",["/users/delete"]],["get_handler",["/users/42"]],["get_handler",["/users/42/photo"]],["get_handler",["/photos"]],["add_handler",["/users/delete"]],["get_handler",["/users/delete"]]]
    Output
    [null,null,"/users/{userId}/photo/{photoId}","/users/delete",null,null,null,null,"/users/delete"]

    Why: /users/42/photo/7 fits the placeholder pattern with userId = 42 and photoId = 7. /users/delete fits only the literal pattern. /users/42 and /users/42/photo have the wrong number of segments, /photos matches nothing, and registering /users/delete again changes nothing.

  2. Example 2
    init
    []
    operations
    [["add_handler",["/a/{x}/{z}"]],["add_handler",["/{y}/b/c"]],["get_handler",["/a/b/c"]]]
    Output
    [null,null,"/a/{x}/{z}"]

    Why: Both patterns match /a/b/c. The first segment where they differ is the first one: literal a in /a/{x}/{z} versus placeholder {y} in /{y}/b/c, so the pattern that is literal there wins.

Constraints

  • 1 <= len(operations) <= 10^5
  • Every pattern and URL starts with / and has at least one segment; pattern segments are never empty
  • Pattern segments are either {name} or contain no braces
  • Any two registered patterns differ in some segment: that segment is {name} in one and not the other, or their literal text differs
  • No pattern or URL contains ?
  • No pattern or URL ends with /
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question