Decompose an IP Range into the Fewest CIDR Blocks
Math & Bit ManipulationAuto-graded · 22 test casesLast 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_ipandlast_ipare 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Work with integers
An IPv4 address is just a 32-bit number. Parse each dotted-decimal string into an integer by shifting and OR-ing the four octets. All subsequent logic is pure arithmetic; convert back to dotted-decimal only when formatting the output.
Step 2 — Greedy tiling
Maintain a pointer start initialized to the integer form of first_ip. On each iteration, pick the largest valid CIDR block that begins at start:
-
Alignment constraint. A block of size
2^krequires the lowkbits ofstartto be zero. The biggest suchkis determined by the lowest set bit ofstart:aligned_size = start & -start. This is the classic bit trick for isolating the rightmost 1-bit; it gives the largest power of two that dividesstart. -
Range constraint. The block must not reach past
last_ip. Computeremaining = end - start + 1and halveblock_sizeuntil it fits. -
Emit. Convert
startback to dotted-decimal, append/{prefix}whereprefix = 32 - log2(block_size), advancestartbyblock_size, and repeat.
Special case: start == 0
0 & -0 evaluates to 0 in Python (and in two's-complement arithmetic generally), so the alignment size would be wrong. Address 0 is divisible by every power of two, meaning the maximum aligned size is 2^32. Handle this with an explicit check.
Why the result is minimal
Any two CIDR blocks are either disjoint or one is nested inside the other — they behave like nodes in a binary prefix trie. Given this nesting property, consider the block in any optimal solution that covers start. It cannot begin before start, so it must start exactly at start. Its size is therefore at most the greedy block size B. If it were smaller, the greedy block [start, start + B) would fall entirely within the range, and every optimal block touching that interval would be nested inside it. Replacing them all with the single greedy block cannot increase the block count. Repeating this argument over the rest of the range shows greedy is never worse than any alternative — so it is minimal.
Complexity
- Block count. At most
2 × 32 - 2 = 62blocks for IPv4. Block sizes grow asstartaccumulates trailing zeros, then shrink as the remaining count tightens nearend; each power of two appears at most once in each phase. - Time. Each iteration does at most 32 halvings, so the loop body runs in O(W) where W = 32. With at most O(W) blocks, the total is O(W²) — effectively constant for fixed-width addresses.
- Space. O(W) for the output list; O(1) extra working memory.
Edge cases
| Situation | Behavior |
|---|---|
Single address (first_ip == last_ip) | remaining = 1; block halves to size 1; output is ["x.x.x.x/32"] |
first_ip = "0.0.0.0" | Explicit check sets aligned_size = 2^32 |
Full range 0.0.0.0–255.255.255.255 | remaining = 2^32; single block "0.0.0.0/0" |
Range ending at 255.255.255.255 | After the last block start becomes 2^32 > end; loop exits cleanly |
Reference solution
from typing import List
def get_minimal_cidrs(first_ip: str, last_ip: str) -> List[str]:
def ip_to_int(ip: str) -> int:
value = 0
for octet in ip.split('.'):
value = (value << 8) | int(octet)
return value
def int_to_ip(value: int) -> str:
return '.'.join(str((value >> shift) & 255) for shift in (24, 16, 8, 0))
start = ip_to_int(first_ip)
end = ip_to_int(last_ip)
result = []
while start <= end:
# Largest power-of-two block that `start` is aligned to.
# `start & -start` extracts the lowest set bit, which equals
# the maximum aligned block size. Address 0 has no set bits,
# so handle it explicitly as 2^32.
aligned_size = start & -start
if aligned_size == 0:
aligned_size = 1 << 32
# Shrink until the block fits within the remaining address count.
remaining = end - start + 1
block_size = aligned_size
while block_size > remaining:
block_size >>= 1
# block_size == 2^k, so prefix length == 32 - k.
prefix = 32 - (block_size.bit_length() - 1)
result.append(f'{int_to_ip(start)}/{prefix}')
start += block_size
return result