00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each call to iterator() returns a new iterator with its own position, so the same Range can be looped over many times, even in nested loops.

Approaches

Both approaches make Range iterable. The first writes the iterator by hand; the second reuses the iterator of an IntStream.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Both iterators produce each value in constant time and store only their current position, so iterating over a range of n values costs O(n) time and O(1) memory.

Interview Tips and Recommended Approach

  • Return a new iterator each time. Storing the position in Range itself breaks nested loops.
  • Throw NoSuchElementException from next() at the end, as the contract requires.
  • Leave remove() alone if removal makes no sense; its default throws UnsupportedOperationException.
  • Mention fail-fast iterators. JDK collections throw ConcurrentModificationException when changed during iteration.

Recommended Approach: Hand-Written Iterator

Why: it shows the full iterator contract in a few lines, which makes it the best answer when the question is about how for-each loops work.