Nested List Iterator With Remove
AirbnbPhone screenMedium
Build NestedListIterator over data, a list of lists of integers. It walks the integers in row-major order: the first inner list from left to right, then the second, and so on. Inner lists can be empty, and so can data.
Besides the usual has_next() and next(), it supports remove(), which deletes from data the integer that the most recent successful next() returned. The deletion happens in the list the caller gave you, in place, not in a copy of it, and the iterator must carry on correctly afterwards: removing an integer never makes it skip or repeat another one.
Part 1: Iterator with remove
Implement the class:
has_next()returns whether any integer has not been returned yet. It can be called any number of times in a row, and calling it changes nothing about whatnext()orremove()do.next()returns the next integer in row-major order, and raisesStopIterationwhen none is left.remove()deletes, from the inner list it came from, the integer that the most recent successfulnext()returned. Each successfulnext()allows oneremove(). Aremove()raisesRuntimeErrorwhen there is nothing to remove: before the firstnext(), or when the integer returned by the latest successfulnext()has already been removed. Anext()that raisedStopIterationdoes not count as a call here, so the last integer returned can still be removed after it. Returns nothing.contents()returnsdata, the same list object you were given.
The integers still to come after a remove() are the same ones, in the same order, as if it had not been called.
- Example 1
- init
[[[],[1,2,3],[4,5]]]- operations
[["next",[]],["next",[]],["remove",[]],["next",[]],["next",[]],["next",[]],["has_next",[]],["contents",[]]]- Output
[1,2,null,3,4,5,false,[[],[1,3],[4,5]]]
Why: The first two next() calls return 1 and 2. remove() deletes the 2 from the list, leaving [1, 3] in the middle row, and the iterator carries on with 3, 4, 5. After 5, has_next() is false, and contents() shows the list the iterator was given with the 2 gone.
Constraints
0 <= len(data) <= 10^4- The total number of integers is at most
10^5 1 <= len(operations) <= 10^5