Simulate IPv4 CIDR Block Iterator
Math & Bit ManipulationAuto-graded · 14 test casesLast 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":argumentscontains[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 appendsNoneto the output list."next":argumentscontains[]. 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).
operationscontains 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`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
An IPv4 address is fundamentally a 32-bit unsigned integer formatted as four 8-bit octets separated by dots. Instead of managing carry-over logic across individual octets during string generation, we can convert the IP address and its subnet mask into integer ranges:
- CIDR to Integer Range:
- For prefix length $n$, the upper $n$ bits are fixed (the subnet mask).
- The starting numerical address (network address) has all $32 - n$ lower host bits set to
0. - The ending numerical address (broadcast address) has all $32 - n$ lower host bits set to
1.
- State Management:
- We store the state as two integer cursors:
currentandend. - On
"init", we parse the CIDR string (using Python's built-inipaddressmodule or bitwise shifts), obtain the starting and ending integers, setcurrent = startandend = broadcast, and returnNone. - On
"next", ifcurrentis valid andcurrent <= end, we convertcurrentback into dotted-decimal format, append it to the result list, and incrementcurrent += 1. Ifcurrent > endor ifinithas not been called, we record"StopIteration".
- We store the state as two integer cursors:
Complexity
- Time Complexity:
"init": $O(1)$ per initialization since parsing a fixed 32-bit structure takes constant work."next": $O(1)$ per call since converting an integer to an IP string takes $O(1)$ operations.- Overall Time Complexity: $O(M)$ where $M$ is the number of operations.
- Space Complexity: $O(1)$ auxiliary space for tracking the iterator state (
currentandend).
Python Solution
import ipaddress
from typing import List, Optional
def ipv4_cidr_iterator(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]:
results: List[Optional[str]] = []
current: Optional[int] = None
end: Optional[int] = None
for op, args in zip(operations, arguments):
if op == "init":
# strict=False ensures host bits are masked to obtain network address
network = ipaddress.IPv4Network(args[0], strict=False)
current = int(network.network_address)
end = int(network.broadcast_address)
results.append(None)
elif op == "next":
if current is None or current > end:
results.append("StopIteration")
else:
results.append(str(ipaddress.IPv4Address(current)))
current += 1
else:
raise ValueError(f"Unsupported operation: {op}")
return results