IP to CIDR Problem
Description
LeetCode Problem 751.
An IP address is a formatted 32-bit unsigned integer where each group of 8 bits is printed as a decimal number and the dot character '.' splits the groups.
- For example, the binary number
00001111 10001000 11111111 01101011(spaces added for clarity) formatted as an IP address would be"15.136.255.107".
A CIDR block is a format used to denote a specific set of IP addresses. It is a string consisting of a base IP address, followed by a slash, followed by a prefix length k. The addresses it covers are all the IPs whose first k bits are the same as the base IP address.
- For example,
"123.45.67.89/20"is a CIDR block with a prefix length of20. Any IP address whose binary representation matches01111011 00101101 0100xxxx xxxxxxxx, wherexcan be either0or1, is in the set covered by the CIDR block.
You are given a start IP address ip and the number of IP addresses we need to cover n. Your goal is to use as few CIDR blocks as possible to cover all the IP addresses in the inclusive range [ip, ip + n - 1] exactly. No other IP addresses outside of the range should be covered.
Return the shortest list of CIDR blocks that covers the range of IP addresses. If there are multiple answers, return any of them.
Example 1:
Input: ip = "255.0.0.7", n = 10
Output: ["255.0.0.7/32","255.0.0.8/29","255.0.0.16/32"]
Explanation:
The IP addresses that need to be covered are:
- 255.0.0.7 -> 11111111 00000000 00000000 00000111
- 255.0.0.8 -> 11111111 00000000 00000000 00001000
- 255.0.0.9 -> 11111111 00000000 00000000 00001001
- 255.0.0.10 -> 11111111 00000000 00000000 00001010
- 255.0.0.11 -> 11111111 00000000 00000000 00001011
- 255.0.0.12 -> 11111111 00000000 00000000 00001100
- 255.0.0.13 -> 11111111 00000000 00000000 00001101
- 255.0.0.14 -> 11111111 00000000 00000000 00001110
- 255.0.0.15 -> 11111111 00000000 00000000 00001111
- 255.0.0.16 -> 11111111 00000000 00000000 00010000
The CIDR block "255.0.0.7/32" covers the first address.
The CIDR block "255.0.0.8/29" covers the middle 8 addresses (binary format of 11111111 00000000 00000000 00001xxx).
The CIDR block "255.0.0.16/32" covers the last address.
Note that while the CIDR block "255.0.0.0/28" does cover all the addresses, it also includes addresses outside of the range, so we cannot use it.
Example 2:
Input: ip = "117.145.102.62", n = 8
Output: ["117.145.102.62/31","117.145.102.64/30","117.145.102.68/31"]
Constraints:
7 <= ip.length <= 15ipis a valid IPv4 on the form"a.b.c.d"wherea,b,c, anddare integers in the range[0, 255].1 <= n <= 1000- Every implied address
ip + x(forx < n) will be a valid IPv4 address.
Solution
Approach: Greedy Largest Aligned Block
A CIDR block with prefix length k covers 2^(32 - k) addresses, and its base address must be a multiple of that size (the last 32 - k bits are free, so they must be 0 in the base). So the question becomes: split the range [start, start + n - 1] into as few blocks as possible, where each block has a power-of-two size and starts at a multiple of its size.
Convert ip to a 32-bit number start. Then repeat while addresses are left:
- Find the largest
sizethat is a power of two, dividesstart, and is at mostn. Start fromsize = 1and keep doubling whilestartis a multiple of2 * sizeand2 * size <= n. - Output the block
start/(32 - log2(size)), written back as four octets. - Move on:
start += size,n -= size.
Taking the largest possible block every time is optimal. A larger block at start would either not be aligned (it would cover addresses before start) or be too big (it would cover addresses after the range). And any smaller block would leave the rest of this aligned chunk to be covered by more blocks.
Note that start = 0 is a multiple of every size, so the size <= n bound is what stops the doubling there. In example 1, 255.0.0.7 is odd, so the first block has size 1; then 255.0.0.8 allows size 8, and the single address 255.0.0.16 is left.
Complexity: Each step at least doubles the alignment of start or shrinks the remaining count, so there are O(log n) blocks, each found in O(log n) steps: O(log2 n) time, apart from the output.
class Solution:
def ipToCIDR(self, ip: str, n: int) -> List[str]:
start = 0
for part in ip.split("."):
start = start * 256 + int(part)
ans = []
while n > 0:
# The largest block that starts at `start`: its size must divide `start` and must not exceed n.
size = 1
while start % (size * 2) == 0 and size * 2 <= n:
size *= 2
prefix = 32 - (size.bit_length() - 1)
octets = [str((start >> shift) & 255) for shift in (24, 16, 8, 0)]
ans.append(".".join(octets) + "/" + str(prefix))
start += size
n -= size
return ans