Skip to content
Coding · Medium · Networking · Target O(n log n + pairs) · Senior

CIDR overlap detector

Parse IPv4 CIDR blocks by hand and report every pair that overlaps, saying which block holds which. Malformed blocks are rejected.

Statement

A firewall rule, a route table and a request to peer two networks all go wrong the same way: two address ranges that were meant to be separate overlap. Write find_overlaps(blocks), where blocks is a list of IPv4 CIDR strings such as "10.20.0.0/16". Return one (i, j, relation) for every pair of positions i < j whose blocks share at least one address, ordered by i and then by j.

relation describes blocks[i] against blocks[j]: "equal" when they are the same block, "contains" when blocks[i] is the larger block and holds all of blocks[j], and "inside" when it is the other way round. Host bits are cleared before comparing, so "10.1.2.3/8" means the block 10.0.0.0/8.

The bit arithmetic is the point, so do not import the ipaddress module. Raise ValueError if any block is malformed, even when nothing overlaps.

Examples

blocks = ["10.20.0.0/16", "10.0.0.0/8", "192.168.1.0/24",
          "10.20.30.0/24", "172.16.0.0/12", "192.168.1.128/25"]
→ [(0, 1, "inside"), (0, 3, "contains"), (1, 3, "contains"), (2, 5, "contains")]

["192.168.0.0/24", "192.168.1.0/24"]  → []                      # neighbours share no address
["10.1.2.3/8", "10.0.0.0/16"]         → [(0, 1, "contains")]    # host bits cleared
["10.0.0.256/24"]                     → ValueError

Constraints

A block is four decimal octets from 0 to 255 separated by dots, then a slash, then a prefix length from 0 to 32. Every number is plain ASCII digits with no sign, no spaces and no leading zeros (0 on its own is fine), so "010.0.0.0/8", " 10.0.0.0/8" and "10.0.0.0/08" are all malformed.

Up to 1,000 blocks. The answer can hold every pair, so comparing every pair is acceptable; be ready to say how you would do better when overlaps are rare.

Free to try · sign in to save your attemptSolve it in the editor with visible tests
Open in the app