Skip to the code
cf.
+25 XP

#737 Most Specific Route Wins

medium

Modern routers don't simply pick the first route that matches; they pick the most specific one, so /users/new beats /users/:id whatever order they are listed in.

A pattern matches a path with the usual rules: segments split on / (empty pieces ignored), plain segments must be equal, :name matches any one segment, and a final * matches the rest, even nothing. Among all matching patterns, compare two of them segment by segment from the left: at the first position where their kinds differ, a plain segment beats a :param, which beats *, and a pattern that has already ended beats one that has a * there. If they never differ, the one listed first wins.

Write bestRoute(routes, path) that returns the winning pattern string, or null if none matches.

Example 1

Input: routes = ["/users/:id","/users/new","/*"], path = "/users/new"
Output: "/users/new"

All three match. At the second segment, plain new beats :id, and both beat * at the first segment.

Example 2

Input: routes = ["/users/:id","/users/new"], path = "/users/7"
Output: "/users/:id"

Only the parameter route matches 7.

Constraints

  • 0 <= routes.length <= 1000; patterns and paths are up to 200 characters.
  • * only appears as the last segment of a pattern.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).