Bidirectional Walk Over a CIDR Block's Addresses
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a two-way cursor over the IPv4 addresses of a CIDR block using integer arithmetic, with exact boundary and no-move-on-failure rules.
Walking a CIDR Block
An IPv4 CIDR block such as 192.168.1.0/24 covers a contiguous run of addresses. You are given a CIDR string and a list of cursor commands. Simulate a bidirectional cursor moving over the block's addresses in ascending numeric order, and report what each command produces.
Block definition
- The block consists of every address from the network address (all host bits zero) to the broadcast address (all host bits one), inclusive.
- The input address may have host bits set, for example
192.168.1.254/30. Normalize it to the network address. That block is192.168.1.252through192.168.1.255. - Do not materialize the list of addresses. A
/0block holds 2^32 addresses.
Cursor model
Picture the cursor as sitting between addresses. It starts just before the first address of the block.
"next": if an address lies after the cursor, return it as a dotted-decimal string and move the cursor past it. If the cursor is already after the last address, the result is the string"StopIteration"and the cursor does not move."prev": if an address lies before the cursor, move the cursor back over it and return that address as a dotted-decimal string. If the cursor is before the first address, the result is the string"StopIteration"and the cursor does not move.
Consequently, after next, next, a prev returns the same address that the second next returned. A failed command never changes the cursor, so the walk can continue normally afterwards.
Task
Implement cidr_cursor_walk(cidr, commands, arguments). Process commands in order and return a list of strings, one per command, holding either the dotted-decimal address or "StopIteration".
arguments[i] is the argument list for commands[i]. It is always empty for these two commands and can be ignored.
If cidr is not a valid IPv4 CIDR, raise ValueError. If a command is neither "next" nor "prev", raise ValueError.
Constraints
cidris an IPv4 address followed by/and a prefix length from 0 to 32.commandscontains only"next"and"prev".len(arguments) == len(commands), and every inner list is empty.- Memory use must not depend on the block size.
- Addresses are output in standard dotted-decimal form without leading zeros, for example
10.0.0.7.
Examples
Example 1
Input: cidr_cursor_walk('192.168.1.254/30', ['next', 'next', 'prev'], [[], [], []])
Output: ['192.168.1.252', '192.168.1.253', '192.168.1.253']
Example 2
Input: cidr_cursor_walk('10.0.0.0/32', ['next'], [[]])
Output: ['10.0.0.0']
Example 3
Input: cidr_cursor_walk('192.168.1.0/30', ['prev'], [[]])
Output: ['StopIteration']
Hints
Hint 1
Treat each address as a 32-bit unsigned integer. A CIDR block is then one contiguous integer interval from the network address to the broadcast address.
Hint 2
Keep a single integer cursor equal to the address that `next` would return. `next` returns it and then increments. `prev` decrements first and then returns the address it lands on.
Hint 3
Check bounds before moving. `next` fails when the cursor is past the last address, and `prev` fails when the cursor is at the first address. In both cases leave the cursor unchanged.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat an IPv4 address as a 32-bit unsigned integer. A CIDR block a.b.c.d/n is then one contiguous interval of integers:
host_bits = 32 - n- the network address is the input address with its low
host_bitsbits cleared - the broadcast address is the network address plus
2^host_bits - 1
The ipaddress module computes both endpoints, with strict=False so that input with host bits set is normalized to the network address.
The whole state is one integer, cursor. It holds the address that the next next would return. It starts at the first address and can range from first to last + 1.
next: ifcursor <= last, returncursorand then increment it. Otherwise return"StopIteration"and leave the cursor alone.prev: ifcursor > first, decrement it and return the address now under it. Otherwise return"StopIteration"and leave the cursor alone.
Addresses are converted back to dotted-decimal text only when they are reported.
Why it is correct
The cursor sits between addresses, and the integer cursor is the index of the address immediately to its right. next returns that right-hand address and steps over it. prev steps back over the left-hand address and returns it. This is why next, next, prev yields .252, .253, .253: prev re-reports the address the second next just passed.
Because the bounds checks come before any change to the cursor, a failed command has no side effect. After exhausting the block with next, the cursor is last + 1, so prev correctly returns last.
For a /32 block, first == last. The first next returns the address and a second next fails. prev fails at the start, and after one next it returns the same address again.
For a /0 block, the range is 0.0.0.0 to 255.255.255.255 and the solution still uses constant memory.
Complexity
- Time: O(1) per command, so O(m) for m commands.
- Space: O(1) beyond the output list, regardless of block size.
Reference solution
import ipaddress
from typing import List
def cidr_cursor_walk(cidr: str, commands: List[str], arguments: List[List]) -> List[str]:
network = ipaddress.ip_network(cidr, strict=False)
if not isinstance(network, ipaddress.IPv4Network):
raise ValueError("CIDR must be IPv4")
first = int(network.network_address)
last = int(network.broadcast_address)
cursor = first # integer value of the address that "next" would return
results = []
for command in commands:
if command == "next":
if cursor > last:
results.append("StopIteration")
else:
results.append(str(ipaddress.IPv4Address(cursor)))
cursor += 1
elif command == "prev":
if cursor <= first:
results.append("StopIteration")
else:
cursor -= 1
results.append(str(ipaddress.IPv4Address(cursor)))
else:
raise ValueError("Unknown operation")
return results