Katkat

Convert IPv4 Ranges to CIDR Blocks

OpenAIBackend Engineer · Technical Screen

Last updated

This question evaluates understanding of IPv4 addressing, binary/bitwise manipulation, and the ability to summarize consecutive address ranges into minimal CIDR blocks, and belongs to the Coding & Algorithms domain for backend engineering roles.

Implement a function that summarizes a consecutive IPv4 address range using the smallest possible list of CIDR blocks.

You are given:

  • start_ip: a valid IPv4 address string such as "192.168.0.7".
  • count: a positive integer representing how many consecutive addresses must be covered, starting exactly at start_ip.

Return a list of CIDR block strings that cover exactly the addresses from start_ip through the next count - 1 addresses, without including any address before start_ip or after the range.

A CIDR block has the form a.b.c.d/prefix, where prefix is between 0 and 32. For example, "192.168.0.8/29" represents 8 addresses starting at 192.168.0.8.

Requirements:

  1. Treat IPv4 addresses as unsigned 32-bit values.
  2. At each step, choose a block that starts at the current address, is correctly aligned for its size, and does not exceed the remaining range.
  3. Return a minimal-length list of CIDR blocks.
  4. Include unit tests for edge cases such as a single address, unaligned starts, ranges crossing octet boundaries, and ranges ending near 255.255.255.255.

Example:

Input:

start_ip = "255.0.0.7"
count = 10

Output:

[
 "255.0.0.7/32",
 "255.0.0.8/29",
 "255.0.0.16/32"
]

Explanation: The output covers exactly 10 addresses starting at 255.0.0.7. It must not round the first block down to an earlier network boundary, because that would include addresses before the input address.