KatInterview

Cover an IPv4 Address Run with the Fewest Prefix Blocks

Math & Bit ManipulationAuto-graded · 22 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationgreedyipv4

Last 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 at first_ip and contains total addresses: first_ip and the total - 1 addresses 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

  1. Treat every address as an unsigned 32-bit integer (the first octet is the most significant byte).
  2. A block with prefix length p contains 2^(32 - p) consecutive addresses, and its first address must be a multiple of that size (the block is aligned).
  3. 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.
  4. The list must have the minimum possible number of blocks. List the blocks in increasing address order.
  5. 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_ip is 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.