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.
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.
Input: routes = ["/users/:id","/users/new"], path = "/users/7" Output: "/users/:id"
Only the parameter route matches 7.
0 <= routes.length <= 10^5; patterns and paths are up to 200 characters.* only appears as the last segment of a pattern.Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #737 Most Specific Route Wins. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.