OpenAI questions

IPv4 Address Iterator

OpenAIPhone screenMedium

IPv4 addresses are written as four dotted decimal octets a.b.c.d, each from 0 to 255, such as 10.0.0.254. Read as a single 32-bit number, an address is a * 2^24 + b * 2^16 + c * 2^8 + d, and addresses are ordered by that number. The smallest address is 0.0.0.0 and the largest is 255.255.255.255.

Build the class IPv4Iterator. Each test drives one instance through a sequence of calls and checks every return value. When next() has no address left, it raises StopIteration.

Part 1: Forward iterator

You are given a valid address string start. Implement:

  • has_next() returns true while some address has not been returned yet.
  • next() returns the next address as a string. The first call returns start itself, and each later call returns the address one higher, up through 255.255.255.255. When no address is left, next() raises StopIteration.

The walk is in numeric order as 32-bit numbers, so incrementing carries across octets: 10.0.0.255 is followed by 10.0.1.0, and 1.2.3.255 by 1.2.4.0.

  1. Example 1
    init
    ["10.0.0.254"]
    operations
    [["has_next",[]],["next",[]],["next",[]],["next",[]],["has_next",[]],["next",[]]]
    Output
    [true,"10.0.0.254","10.0.0.255","10.0.1.0",true,"10.0.1.1"]

    Why: The last octet 254 becomes 255, then the next call carries into the third octet. After three returns has_next() is still true and the following next() returns 10.0.1.1.

Constraints

  • start is a valid address with octets written without leading zeros
  • 1 <= len(operations) <= 100
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
IPv4 Address Iterator: OpenAI interview question | LoopCoach