Design an IPv4 Address Iterator
Company: Anthropic
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to represent and iterate IPv4 addresses, covering parsing, numeric arithmetic with carry between octets, and the design of a stateful iterator.
Constraints
- All input IP strings are valid IPv4 addresses with octets in the range 0 to 255.
- `start_ip` is less than or equal to `end_ip` in numeric IPv4 order.
- `step` is a positive integer.
- The number of returned addresses will not exceed 10^5.
Examples
Input: ('192.168.0.254', '192.168.1.4', 2)
Expected Output: ['192.168.0.254', '192.168.1.0', '192.168.1.2', '192.168.1.4']
Explanation: Starting at 192.168.0.254 and adding 2 each time gives 192.168.1.0, then 192.168.1.2, then 192.168.1.4.
Input: ('10.0.0.255', '10.0.1.1', 1)
Expected Output: ['10.0.0.255', '10.0.1.0', '10.0.1.1']
Explanation: Incrementing 10.0.0.255 by 1 carries into the next octet, producing 10.0.1.0.
Input: ('0.0.0.0', '0.0.0.0', 5)
Expected Output: ['0.0.0.0']
Explanation: The start and end are the same, so the iterator yields exactly one address.
Input: ('1.2.3.4', '1.2.3.10', 20)
Expected Output: ['1.2.3.4']
Explanation: After returning the start address, advancing by 20 would go past the end, so no more addresses are produced.
Input: ('0.255.255.255', '1.0.0.3', 2)
Expected Output: ['0.255.255.255', '1.0.0.1', '1.0.0.3']
Explanation: Adding 2 to 0.255.255.255 carries across multiple octets and produces 1.0.0.1.
Hints
- Think of an IPv4 address as a single 32-bit integer, with each octet representing one byte.
- If you convert `start_ip` and `end_ip` once at the beginning, advancing by `step` becomes simple integer addition.