IP to CIDR - Problem

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 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 consists 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 of 20. Any IP address whose binary representation matches 01111011 00101101 0100xxxx xxxxxxxx (where x can be either 0 or 1) is covered by this CIDR block.

Given a start IP address ip and the number of IP addresses we need to cover n, return the shortest list of CIDR blocks that covers all IP addresses in the inclusive range [ip, ip + n - 1] exactly. No other IP addresses outside of the range should be covered.

Input & Output

Example 1 — Basic Range
$ Input: ip = "255.255.255.7", n = 10
Output: ["255.255.255.7/32","255.255.255.8/29","255.255.255.16/32"]
💡 Note: Start at 255.255.255.7 (binary ends in ...111, no trailing zeros), so single IP block /32. Then 255.255.255.8 (ends in ...1000, 3 trailing zeros) can use /29 block covering 8 IPs. Finally, one more /32 for the remaining IP.
Example 2 — Small Range
$ Input: ip = "1.1.1.1", n = 1
Output: ["1.1.1.1/32"]
💡 Note: Single IP address gets a /32 CIDR block covering exactly that one IP.
Example 3 — Aligned Range
$ Input: ip = "192.168.1.0", n = 4
Output: ["192.168.1.0/30"]
💡 Note: Starting IP ends in ...00 (2 trailing zeros), and we need exactly 4 IPs (2²), so one /30 block perfectly covers the range 192.168.1.0 to 192.168.1.3.

Constraints

  • ip is a valid IPv4 address
  • 1 ≤ n ≤ 1000
  • The range [ip, ip + n - 1] will not overflow

Visualization

Tap to expand
IP to CIDR: Convert IP Range to Optimal Blocks255.255.255.7Start IPn=10CountConvert["255.255.255.7/32", "255.255.255.8/29", "255.255.255.16/32"]Optimal CIDR BlocksIP Range Analysis:7: 1 IP (/32)8-15: 8 IPs (/29)16: 1 IP (/32)Result: 3 CIDR blocks (instead of 10 individual blocks)
Understanding the Visualization
1
Input
Start IP and count of consecutive IPs needed
2
Process
Use bit manipulation to find optimal CIDR block sizes
3
Output
Minimal list of CIDR blocks covering the range
Key Takeaway
🎯 Key Insight: Use trailing zeros in IP binary representation to determine maximum possible block size, then apply greedy selection for optimal coverage.
Asked in
Google 25 Amazon 20 Microsoft 15
18.5K Views
Medium Frequency
~35 min Avg. Time
580 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen