KatInterview

Decompose an IP Range into the Fewest CIDR Blocks

Math & Bit ManipulationAuto-graded · 22 test cases
HardAuto-gradedMath & Bit Manipulationbit-manipulationgreedynetworking

Last updated

Tests greedy interval tiling and bit manipulation by converting an inclusive IPv4 address range into the minimum list of valid, aligned CIDR blocks.

Problem

You are given two IPv4 addresses, first_ip and last_ip, representing the inclusive start and end of a contiguous address range. Return the smallest possible list of CIDR blocks whose union covers exactly that range — no more, no fewer addresses.

Each CIDR block is written in the form a.b.c.d/p, where p is the prefix length.

Background

An IPv4 address is a 32-bit unsigned integer written as four decimal octets. A CIDR block a.b.c.d/p pins the top p bits and lets the remaining 32 - p bits vary freely, so it represents exactly 2^(32 - p) consecutive addresses. For the block to be valid, those free bits must all be zero in the starting address — in other words, a block of 2^k addresses must begin at an address that is a multiple of 2^k.

Task

Implement a function that takes two IP strings and returns the minimal covering list of CIDR strings. The blocks must appear in ascending order (which the greedy approach produces naturally).

Constraints

  • first_ip and last_ip are valid IPv4 address strings.
  • first_ip ≤ last_ip (the range contains at least one address).
  • The range may be as small as a single address or as large as the entire 32-bit space (0.0.0.0–255.255.255.255).
  • The returned list must cover exactly the given range — no gaps, no addresses outside it.
  • Blocks must be returned in the order they appear (ascending by start address).
  • The list must be minimal: no valid covering with fewer blocks exists.

Examples

Example 1

Input: get_minimal_cidrs('192.168.0.0', '192.168.0.5')

Output: ['192.168.0.0/30', '192.168.0.4/31']

Example 2

Input: get_minimal_cidrs('10.0.0.0', '10.0.0.255')

Output: ['10.0.0.0/24']

Example 3

Input: get_minimal_cidrs('192.168.1.10', '192.168.1.10')

Output: ['192.168.1.10/32']

Example 4

Input: get_minimal_cidrs('0.0.0.0', '255.255.255.255')

Output: ['0.0.0.0/0']

Hints

Hint 1

Convert both IP strings to plain 32-bit integers first. All the interesting logic lives in arithmetic, not string parsing.

Hint 2

At each step, the block you pick must satisfy two constraints simultaneously: it must be aligned (the low k bits of the start address are zero) and it must not overshoot the end. The largest aligned block size starting at `start` is given by the lowest set bit: `start & -start`. Cap that by the remaining count and you have your block.

Hint 3

Be careful when `start` is 0: `0 & -0` is 0, not `2^32`. Treat that case explicitly so you don't produce an infinite loop or a wrong block size.