IP Routing Lookup
MediumTrie · Snowflake
A router has a table routes, where each entry is [cidr, name]. A cidr such as "10.20.0.0/16" is an IPv4 address followed by a prefix length p (0 <= p <= 32). An address matches the route if its first p bits equal the first p bits of the route's address. A /0 route matches every address.
For each address in ips, return the name of the matching route with the longest prefix length. If the same block appears more than once in the table, the entry that comes first wins. If no route matches, return None for that address.
Return the answers in the same order as ips.
Every route address has all bits after its prefix set to zero (so "10.20.0.0/16" is valid but "10.20.3.0/16" will not appear). All addresses are valid dotted-quad IPv4 strings.
Example 1
- Input:
- routes = [["10.0.0.0/8", "corp"], ["10.20.0.0/16", "lab"], ["10.20.30.0/24", "rack"], ["0.0.0.0/0", "internet"]], ips = ["10.20.30.40", "10.20.99.1", "10.99.0.1", "8.8.8.8"]
- Output:
- ["rack", "lab", "corp", "internet"]
- Explanation
10.20.30.40matches all four routes and/24is the longest.10.20.99.1is outside the/24but inside the/16.10.99.0.1only matches/8and/0, and8.8.8.8only matches the default/0route.
Example 2
- Input:
- routes = [["192.168.1.0/24", "office"]], ips = ["192.168.1.200", "192.168.2.1"]
- Output:
- ["office", None]
- Explanation
- The first address shares its first 24 bits with the route. The second differs in the third octet, and no other route exists, so it gets
None.
Example 3
- Input:
- routes = [["172.16.0.0/12", "first"], ["172.16.0.0/12", "second"]], ips = ["172.31.255.255"]
- Output:
- ["first"]
- Explanation
- A
/12starting at172.16.0.0covers172.16.0.0to172.31.255.255. Both entries describe the same block, so the earlier one wins.
Constraints
- 0 ≤
routes.length≤ 105 - 0 ≤
ips.length≤ 105 - 0 ≤ prefix length ≤ 32
- Route names are non-empty strings