PIXELBANKv9.1.0
Menu

Problem Statement

A router forwards a packet using the routing entry with the longest matching prefix. Given a routing table and a destination IP, return the chosen next hop.

Background

Each route is (cidr, next_hop). A route matches if the destination is inside its CIDR. Among all matching routes, the one with the largest prefix length wins (most specific). Ties on prefix length are impossible for distinct non-overlapping routes, but if present, the earliest in the table wins. If no route matches, return "drop". A 0.0.0.0/0 route is the default gateway.

Your Task

def route_lookup(table, dest):
  • table: list of (cidr, next_hop).
  • Return the next hop string, or "drop".

Input Format

  • table (list of (str, str)), dest (str).

Output Format

  • A next-hop string or "drop".

Sample

table = [("0.0.0.0/0", "gw"), ("10.0.0.0/8", "r1"), ("10.1.0.0/16", "r2")]
print(route_lookup(table, "10.1.2.3"))

Output:

r2

Example:

Input:
table = [("0.0.0.0/0", "gw"), ("10.0.0.0/8", "r1"), ("10.1.0.0/16", "r2")]
print(route_lookup(table, "10.1.2.3"))
Output:
r2
Reasoning:
  • Convert the destination IP 10.1.2.3 to its integer representation dd by treating the octets as base-256 digits: 10â‹…2563+1â‹…2562+2â‹…256+3=16783822710 \cdot 256^3 + 1 \cdot 256^2 + 2 \cdot 256 + 3 = 167838227.
  • Evaluate the first route 0.0.0.0/0: The prefix length is 00. Since the mask for a /0/0 prefix is 00, the condition (d&0)==(net&0)(d \& 0) == (\text{net} \& 0) holds (0=00=0). As 0>−10 > -1 (initial best prefix), the best match updates to gw with prefix length 00.
  • Evaluate the second route 10.0.0.0/8: The prefix length is 88. The mask is 255.0.0.0255.0.0.0 (or 0xFF0000000xFF000000 in hex). The network part of the destination is 10.0.0.010.0.0.0, which matches the route's network address. Since 8>08 > 0, the best match updates to r1 with prefix length 88.
  • Evaluate the third route 10.1.0.0/16: The prefix length is 1616. The mask is 255.255.0.0255.255.0.0 (or 0xFFFF00000xFFFF0000 in hex). The first 16 bits of the destination 10.1.2.3 correspond to 10.1, which matches the route's network address 10.1.0.0. Since 16>816 > 8, the best match updates to r2 with prefix length 1616.
  • The final output is r2

Constraints:

  • A route matches if dest is within its CIDR.
  • Longest prefix wins; ties -> earliest in table.
  • No match -> "drop".
solution.py

Test Results

0/0
Run code to see test results.