Implement a Removable Nested-List Iterator
Implement an iterator over a mutable array of integer arrays. Traversal goes left to right within each inner array and top to bottom across the outer array. Empty inner arrays are skipped.
Your class must expose:
hasNext() -> bool
next() -> int
remove() -> void
remove() deletes from the original nested-list object the element returned by the most recent successful next().
Required Behavior
-
hasNext()
reports whether another integer remains and may be called repeatedly without advancing the iterator.
-
next()
returns the next integer. It raises an iteration-exhausted exception when no value remains.
-
remove()
is legal exactly once after each successful
next()
.
-
Calling
remove()
before
next()
, or calling it twice after the same
next()
, raises an illegal-state exception.
-
Removing an element must not cause the following element in the same row to be skipped.
-
Mutations made by
remove()
must be visible through the original nested list supplied to the constructor.
Example
data = [[], [1, 2, 3], [4, 5], [], [6]]
it = NestedIterator(data)
it.hasNext() -> true
it.next() -> 1
it.next() -> 2
it.remove()
data -> [[], [1, 3], [4, 5], [], [6]]
it.next() -> 3
Constraints
-
The outer and inner arrays exist for the lifetime of the iterator.
-
Clients do not mutate the nested arrays except through this iterator's
remove()
.
-
Values may repeat; position, not value, identifies what must be removed.
-
Empty outer input is valid.
Hints
-
Maintain a row and column for the next candidate, plus the exact position last returned.
-
Centralize skipping of empty or exhausted rows in one helper.
-
Deleting from the same row shifts later columns left; adjust the cursor accordingly.
Discussion Extensions
-
Give the amortized cost of traversal and the cost of removal for array-backed rows.
-
How would fail-fast behavior work if external mutation had to be detected?
-
What changes if inner collections are linked lists rather than arrays?