Code RoomRoute packet to rule
HardPrep Room Coding #4932

Route packet to rule

CodingNetworking & APIsAlgorithms & data structuresMid–Staff~35 min

A router matches packets against a table of rules. A rule reads address/length, where the address is four numbers from 0 to 255 joined by dots and length runs from 0 to 32. Read an address as a 32 bit number with the first of the four numbers highest. A rule covers a packet when the top length bits of the two addresses agree, and the bits below that are ignored, so 10.0.0.7/24 and 10.0.0.0/24 cover exactly the same packets. Each packet takes the covering rule with the largest length, and the earliest such rule when two lengths tie. Given the rules in table order and the packet addresses, return the chosen rule index for each packet, or -1 when nothing covers it. Aim for a cost per packet that does not grow with the size of the table.

Implement
selected_routes(rules: list[str], packets: list[str]) → list[int]
Examples
in[["0.0.0.0/0","10.0.0.0/8","10.1.0.0/16"],["10.1.2.3","10.2.0.1","8.8.8.8"]]out[2,1,0]
in[["10.0.0.7/24"],["10.0.0.0","10.0.1.0"]]out[0,-1]
in[["192.168.1.0/24","192.168.1.0/24"],["192.168.1.9"]]out[0]
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 35 min
InputExpectedGot
[["0.0.0.0/0","10.0.0.0/8","10.1.0.0/16"],["10.1.2.3","10.2.0.1","8.8.8.8"]][2,1,0]not run yetsample
[["10.0.0.7/24"],["10.0.0.0","10.0.1.0"]][0,-1]not run yetsample
[["192.168.1.0/24","192.168.1.0/24"],["192.168.1.9"]][0]not run yetsample