IP range to CIDR blocks
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Databricks's algorithms (two rounds) round and at OpenAI, last asked Jan 2026. It tests bit manipulation, networking and greedy.
Given a starting IPv4 address and a count n, return the shortest list of CIDR blocks that covers exactly the n consecutive addresses starting there, and no address outside that range. A block a.b.c.d/p covers the 2^(32 - p) addresses that share the first p bits of a.b.c.d, and its base address must have its last 32 - p bits equal to 0.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
range_to_cidrs(ip: str, n: int) -> list[str]— blocks in increasing address order.
Example
range_to_cidrs("255.0.0.7", 10) -> ["255.0.0.7/32", "255.0.0.8/29", "255.0.0.16/32"]
# .7 alone (odd address), .8 to .15 (8 aligned addresses), .16 alone
range_to_cidrs("117.145.102.62", 8) -> ["117.145.102.62/31", "117.145.102.64/30", "117.145.102.68/31"]
range_to_cidrs("10.0.0.0", 256) -> ["10.0.0.0/24"]
Constraints
-
ipis a valid IPv4 address;1 <= n <= 1000, and the range does not go past255.255.255.255.
Clarifying questions
- Is the input a start address and a count, or a start and an end address?
- Should the output be sorted?
- Can the range wrap past the last address?
- IPv6 too?
What a strong answer covers
- Converting the address to a 32-bit integer and back.
- Greedy: at the current address
x, the largest block allowed is limited by alignment, the lowest set bitx & -x(any size whenxis 0), and by the addresses left; shrink it to the largest power of two that fits both, emit it, advance. - Why greedy is optimal: each block is the largest aligned block that starts at
xwithout leaving the range. - O(log n) blocks, each found in O(32).
- Tests:
n = 1, an already aligned range, a start of0.0.0.0, a range ending at255.255.255.255.
Follow-ups
- Take a start and an end address instead of a count.
- Merge a list of arbitrary CIDR blocks into the smallest equivalent list.
- Support IPv6 (128-bit addresses).
Where it's asked
- Databricks · Algorithms (two rounds) · Last asked Jan 202660 min · Live coding in CoderPad or similar
- OpenAI · Agentic coding (beta) · Last asked Oct 2025An existing codebase and changes too large to write by hand; you work through them with an AI coding agent · An AI coding agent is expected
What it tests
bit manipulation · networking · greedy
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.

