KatInterview

Simulate IPv4 CIDR Block Iterator

Math & Bit ManipulationAuto-graded · 14 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationstringsdesign

Last updated

Parse IPv4 CIDR blocks and simulate step-by-step traversal over all IP addresses in the subnet range.

Implement a driver function that simulates the stateful behavior of an IPv4 CIDR subnet iterator over a series of sequential commands.

An IPv4 address consists of four 8-bit octets representing a 32-bit integer. A CIDR notation string specifies an IP address alongside a prefix length $n$ ($0 \le n \le 32$), fixing the top $n$ bits of the address block.

The driver function accepts two parallel lists: operations and arguments.

Supported operations:

  • "init": arguments contains [cidr_str]. Parses the CIDR block, normalizes any host bits (i.e. calculates the subnet base/network address and broadcast address), resets the iteration state to start at the first address of the block, and appends None to the output list.
  • "next": arguments contains []. Advances to and returns the next IPv4 address string (e.g., "192.168.1.0"). If all addresses in the current range have been emitted, or if "init" has not yet been invoked, appends "StopIteration" to the output list.

Constraints

  • $0 \le n \le 32$ for prefix lengths.
  • The iteration state must be maintained across operations in constant $O(1)$ auxiliary space (excluding the returned results).
  • operations contains a sequence of "init" and "next" commands.
  • Host bits provided in the "init" CIDR string should be masked off to find the network start address (e.g., "192.168.1.5/30" starts iteration at "192.168.1.4").

Examples

Example 1

Input: ipv4_cidr_iterator(['init', 'next', 'next', 'next', 'next', 'next'], [['192.168.1.0/30'], [], [], [], [], []])

Output: [None, '192.168.1.0', '192.168.1.1', '192.168.1.2', '192.168.1.3', 'StopIteration']

Example 2

Input: ipv4_cidr_iterator(['init', 'next', 'next'], [['10.0.0.0/32'], [], []])

Output: [None, '10.0.0.0', 'StopIteration']

Hints

Hint 1

Convert the 32-bit IPv4 address into a single 32-bit integer rather than attempting manual string/octet arithmetic.

Hint 2

Use bitwise operations to compute the starting network integer (zero out host bits) and the ending broadcast integer (set host bits to 1).

Hint 3

Maintain state with just two integers (`current` and `end`). Increment `current` on each `next` operation until `current > end`.