/*
Route Pattern Matcher
Approach: Brute Force
R = number of registered routes
U = number of incoming URLs
L = maximum number of path segments
TIME COMPLEXITY: O(U * R * L)
- Preprocessing routes: O(R * L)
- For each of U URLs, check up to R routes.
- Each route comparison takes up to O(L).
- Total: O(R * L + U * R * L)
= O(U * R * L)
SPACE COMPLEXITY:
- Auxiliary Space: O(R * L)
- Including output: O((R + U) * L)
Breakdown:
1. patterns: O(R * L)
Stores the split segments of all R routes.
2. values: O(L)
Stores segments of the current URL.
3. parts: O(1)
const parts = patterns[i];
This creates a REFERENCE to an existing array,
NOT a new array. No O(L) copy is made.
In contrast:
const parts = [...patterns[i]];
This creates a NEW array and takes O(L) space.
4. row: O(L)
Stores the matching route and extracted parameters.
5. isMatch, i, j: O(1)
6. answer: O(U * L)
Stores results for all URLs (output space).
Auxiliary Space:
O(R * L + L + L + 1) = O(R * L)
Note: Complexity uses segment-level analysis,
assuming constant-time segment comparisons.
*/
function matchRoutes(routes, urls) {
// Split all registered routes into segments.
// TC: O(R * L), SC: O(R * L)
const patterns = routes.map(route =>
route.slice(1).split("/")
);
// Stores final output.
// SC: O(U * L), counted as output space.
const answer = [];
// Process each URL.
// U iterations
for (const url of urls) {
// Split current URL into segments.
// TC: O(L), SC: O(L)
const values = url.slice(1).split("/");
// Empty result if no route matches.
// SC: O(L) maximum when populated.
let row = [];
// Check registered routes in original order.
// Up to R routes per URL.
for (let i = 0; i < patterns.length; i++) {
// SC: O(1)
// parts references patterns[i].
// It does NOT create a new array.
const parts = patterns[i];
// Routes with different segment counts
// cannot match.
if (parts.length !== values.length) {
continue;
}
let isMatch = true; // SC: O(1)
// Compare up to L segments.
// TC: O(L) per route.
for (let j = 0; j < parts.length; j++) {
const part = parts[j];
const value = values[j];
// Parameter: {name} matches any segment.
// Literal: must match exactly.
if (!part.startsWith("{") && part !== value) {
isMatch = false;
break;
}
}
// Try the next registered route.
if (!isMatch) {
continue;
}
// Matching route found.
row = [routes[i]];
// Extract parameter names and values.
// TC: O(L), row space: O(L)
for (let j = 0; j < parts.length; j++) {
if (parts[j].startsWith("{")) {
// Remove opening and closing braces.
const name = parts[j].slice(1, -1);
// Add parameter name and URL value.
row.push(name, values[j]);
}
}
// First registered matching route wins.
break;
}
// Add matched row or [].
answer.push(row);
}
return answer;
}
// ---------------- TEST HARNESS ----------------
function runTest(name, routes, urls, expected) {
const actual = matchRoutes(routes, urls);
const passed =
JSON.stringify(actual) === JSON.stringify(expected);
console.log((passed ? "PASS" : "FAIL") + " - " + name);
if (!passed) {
console.log("Expected:", JSON.stringify(expected));
console.log("Actual: ", JSON.stringify(actual));
}
}
// 1. Basic matching - imp.
runTest(
"Basic matching",
["/users/{id}/pictures/{pictureId}", "/health"],
["/users/101/pictures/1", "/health", "/users/1"],
[
["/users/{id}/pictures/{pictureId}",
"id", "101", "pictureId", "1"],
["/health"],
[]
]
);
// 2. First registered match wins - imp.
runTest(
"Registration precedence",
["/users/{id}", "/users/admin"],
["/users/admin"],
[
["/users/{id}", "id", "admin"]
]
);
// 3. Multiple parameters - imp.
runTest(
"Multiple parameters",
["/{type}/{id}"],
["/orders/7"],
[
["/{type}/{id}", "type", "orders", "id", "7"]
]
);
// 4. Different segment counts
runTest(
"Different segment counts",
["/users/{id}"],
["/users/1/photos"],
[[]]
);
// 5. Case-sensitive matching
runTest(
"Case sensitivity",
["/Users/{id}"],
["/users/1"],
[[]]
);
// 6. No matching route - imp.
runTest(
"No matching route",
["/health", "/users/{id}"],
["/products/10"],
[[]]
);
// 7. Literal route registered first
runTest(
"Literal precedence",
["/users/admin", "/users/{id}"],
["/users/admin"],
[["/users/admin"]]
);
// 8. Routes sharing prefixes
runTest(
"Shared prefixes",
["/users/{id}", "/users/{id}/posts/{postId}"],
["/users/5", "/users/5/posts/10"],
[
["/users/{id}", "id", "5"],
["/users/{id}/posts/{postId}",
"id", "5", "postId", "10"]
]
);