← Questions

IP range to CIDR blocks

0
DatabricksOpenAICodingLast asked Jan 2026

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

  • ip is a valid IPv4 address; 1 <= n <= 1000, and the range does not go past 255.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 bit x & -x (any size when x is 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 x without leaving the range.
  • O(log n) blocks, each found in O(32).
  • Tests: n = 1, an already aligned range, a start of 0.0.0.0, a range ending at 255.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

What it tests

bit manipulation · networking · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding