Cover an IPv4 Address Run with the Fewest Prefix Blocks
Math & Bit ManipulationAuto-graded · 22 test casesLast updated
Split a run of consecutive IPv4 addresses into the fewest aligned power-of-two prefix blocks using 32-bit integer and lowest-set-bit reasoning.
Cover an IPv4 Address Run with the Fewest Prefix Blocks
A network engineer needs to describe a run of consecutive IPv4 addresses as a list of CIDR blocks. The list must describe exactly the addresses in the run, no more and no fewer, and it must use as few blocks as possible.
Input
first_ip: a string holding a valid IPv4 address in dotted-decimal form, for example"192.168.0.7".total: a positive integer, the number of consecutive addresses to cover. The run begins atfirst_ipand containstotaladdresses:first_ipand thetotal - 1addresses after it.
Output
Return a list of strings, each of the form a.b.c.d/p, where a.b.c.d is the first address of the block and p is the prefix length (an integer from 0 to 32).
Rules
- Treat every address as an unsigned 32-bit integer (the first octet is the most significant byte).
- A block with prefix length
pcontains2^(32 - p)consecutive addresses, and its first address must be a multiple of that size (the block is aligned). - The blocks together must cover exactly the addresses of the run: no address before
first_ip, none after the end of the run, no gaps and no overlaps. - The list must have the minimum possible number of blocks. List the blocks in increasing address order.
- A block must never be extended backward to an earlier aligned boundary, because that would include addresses before
first_ip.
For example, a block "192.168.0.8/29" holds 8 addresses, from 192.168.0.8 to 192.168.0.15.
Constraints
first_ipis always a valid IPv4 address with four decimal octets, each from 0 to 255.1 <= total- The run fits in the address space: (integer value of
first_ip) +total<= 2^32.
Examples
Example 1
Input: ip_run_to_prefixes('255.0.0.7', 10)
Output: ['255.0.0.7/32', '255.0.0.8/29', '255.0.0.16/32']
Example 2
Input: ip_run_to_prefixes('192.168.0.0', 8)
Output: ['192.168.0.0/29']
Example 3
Input: ip_run_to_prefixes('10.0.0.1', 3)
Output: ['10.0.0.1/32', '10.0.0.2/31']
Hints
Hint 1
Convert the dotted address to a single integer first; carrying across octets then happens automatically with ordinary addition.
Hint 2
At the current address, the largest block that can start there is limited by alignment: the value of the lowest set bit, `cur & -cur`. Address 0 is aligned for any size, up to 2^32.
Hint 3
Shrink that size (halve it) until it is no larger than the number of addresses still uncovered, emit the block with prefix 32 - log2(size), advance, and repeat.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Convert the starting address to an unsigned 32-bit integer and walk through the run from left to right. At each step, take the largest block that:
- starts exactly at the current address, so nothing before the run is included;
- is aligned: a block of size
2^kmust start at a multiple of2^k; - fits in the number of addresses still uncovered.
The alignment limit is the lowest set bit of the current address, obtained with cur & -cur. For example, ...0111 gives 1 and ...1000 gives 8. Address 0 has no set bit and is aligned for every size up to 2^32, so it is handled as a special case.
Start from the aligned size and halve it until it is no larger than the remaining count. The prefix length is 32 - (size.bit_length() - 1). Format the current address, append the block, advance the address by the block size, subtract the size from the remaining count, and repeat until nothing remains.
Why it is correct
Exactness. Each block begins at the current address and the address advances by exactly the block size. Each block is no larger than the remaining count. So the blocks tile the run with no gaps, overlaps, or overshoot, and each block is aligned by construction.
Minimality. Aligned power-of-two blocks are either disjoint or nested. Each greedy block is maximal: its double-size parent either starts before the current address (when alignment was the limit), meaning it would include addresses outside the run or already covered, or it extends past the end of the run (when the count was the limit). Maximal blocks inside the run are pairwise disjoint, and any valid cover consists of aligned blocks inside the run, each of which lies within exactly one greedy block. So every greedy block needs at least one block of its own in any cover, and no cover can be shorter.
Complexity
- Time: the number of blocks is O(log total) (at most about 64 for 32-bit addresses), with at most 32 halvings per block, so O(32 * log total), effectively constant.
- Space: O(1) beyond the output list.
Reference solution
from typing import List
def ip_run_to_prefixes(first_ip: str, total: int) -> List[str]:
parts = [int(p) for p in first_ip.split('.')]
current = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
result = []
remaining = total
while remaining > 0:
if current == 0:
aligned_size = 1 << 32
else:
aligned_size = current & -current
block_size = aligned_size
while block_size > remaining:
block_size >>= 1
prefix = 32 - (block_size.bit_length() - 1)
address = '.'.join(str((current >> shift) & 255) for shift in (24, 16, 8, 0))
result.append(f'{address}/{prefix}')
current += block_size
remaining -= block_size
return result