Convert an IP range to minimal CIDRs
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates understanding of IPv4 address encoding, binary and bitwise operations, and optimal interval covering for expressing consecutive addresses as CIDR blocks. It is commonly asked in the Coding & Algorithms domain to assess practical algorithmic skills in data representation and alignment constraints, focusing on practical application rather than purely conceptual theory.
Constraints
- 0 <= n <= 2^32
- `ip` is a valid IPv4 address
- The range from `ip` to `ip + n - 1` stays within the IPv4 address space
- Use 64-bit-safe arithmetic when needed, since `n` can be as large as 2^32
Examples
Input: ("255.0.0.7", 10)
Expected Output: ["255.0.0.7/32", "255.0.0.8/29", "255.0.0.16/32"]
Explanation: The address 255.0.0.7 is not aligned for a larger block, then 255.0.0.8 can take 8 addresses as /29, and 255.0.0.16 covers the final single address.
Input: ("0.0.0.0", 0)
Expected Output: []
Explanation: No addresses need to be covered, so the minimal answer is an empty list.
Input: ("192.168.1.0", 256)
Expected Output: ["192.168.1.0/24"]
Explanation: The start is aligned to a /24 boundary, and 256 addresses exactly match one /24 block.
Input: ("192.168.1.5", 4)
Expected Output: ["192.168.1.5/32", "192.168.1.6/31", "192.168.1.8/32"]
Explanation: The range covers .5 through .8. Because .5 is unaligned, it must be a /32. Then .6-.7 can be a /31, and .8 is the last /32.
Input: ("0.0.0.1", 3)
Expected Output: ["0.0.0.1/32", "0.0.0.2/31"]
Explanation: The first odd address must be a /32, then the next two aligned addresses can be grouped into a /31.
Input: ("10.0.0.255", 2)
Expected Output: ["10.0.0.255/32", "10.0.1.0/32"]
Explanation: The range crosses an octet boundary. Both addresses are singletons because the start is not aligned for a 2-address block.
Input: ("0.0.0.0", 4294967296)
Expected Output: ["0.0.0.0/0"]
Explanation: Covering the entire IPv4 address space requires exactly one /0 block.
Hints
- It is often easier to solve this by converting the IPv4 address into a 32-bit integer and working with integer ranges.
- At each step, take the largest power-of-two-sized block that is both aligned at the current start address and does not exceed the remaining number of addresses.