IPv4 range iterator with reverse and CIDR support

0
Sign in

An IPv4 address such as "172.16.4.9" is four octets, each 0 to 255. Taken together, the octets form one unsigned 32-bit number.

Build iterators that walk IPv4 addresses lazily, one at a time. The full address space has more than 4 billion entries, so you must not build a list of them.

Part 1: forward iterator

Implement an iterator built from a starting address. It returns that address, then each next address in order, and ends after 255.255.255.255.

  • Support has_next() -> bool and next() -> str. In Python, __iter__/__next__ are fine too.
  • Raise ValueError for a malformed address. A valid address has exactly four parts, and each part is a decimal number from 0 to 255.

Example: starting at "172.16.4.254", the first three calls to next() return "172.16.4.254", "172.16.4.255", "172.16.5.0". Starting at "255.255.255.254", the iterator returns two addresses and then has_next() is False.

Part 2: reverse iterator

Add an iterator that walks downward from a starting address and ends after 0.0.0.0.

Example: starting at "172.16.5.1", it returns "172.16.5.1", "172.16.5.0", "172.16.4.255", and so on.

Part 3: CIDR blocks

A CIDR block "base/p" (with 0 <= p <= 32) contains every address whose first p bits match the first p bits of base. Iterate over all addresses in a block in either direction. You may also be given a start address inside the block.

Example: "172.16.4.0/30" contains 172.16.4.0 through 172.16.4.3. Forward from "172.16.4.2" it returns "172.16.4.2", "172.16.4.3". In reverse with no start address, it returns .3, .2, .1, .0.

Part 4: discussion

Give the time and space cost of each operation. Explain how your design behaves on very large blocks, such as /8 or /0.

OpenAICodingMediumLast asked Sep 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.