You are given a nested list of integers. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator
class:
NestedIterator(List<NestedInteger> nestedList)
Initializes the iterator with the nested list nestedList
.int next()
Returns the next integer in the nested list.boolean hasNext()
Returns true
if there are still some integers in the nested list and false
otherwise.Your code will be tested with the following pseudocode:
initialize the nestedList with a NestedIterator
repeat the following while nestedList.hasNext():
print(nestedList.next())
This will generate output of all the integers in the nested list in the same order they appear in the nested list.
NestedInteger
?
NestedInteger
is a class with the following methods:
isInteger()
: Returns true
if this NestedInteger
holds a single integer, rather than a nested list.getInteger()
: Returns the single integer that this NestedInteger
holds, if it holds a single integer. The result is undefined if this NestedInteger
holds a nested list.getList()
: Returns the nested list that this NestedInteger
holds, if it holds a nested list. The result is undefined if this NestedInteger
holds a single integer.hasNext()
should return false
.The goal is to flatten out a nested list structure such that we can iterate over all the integers within. A useful approach is to use a stack to maintain the position within the nested lists.
Here’s the overall approach:
__init__
):
next
):
hasNext()
confirms that there is a next integer, simply return it.hasNext
):
NestedInteger
, check if it is an integer or a list:
class NestedIterator:
def __init__(self, nestedList):
self.stack = [iter(nestedList)]
self.next_element = None
def next(self):
if not self.hasNext():
raise StopIteration
result = self.next_element
self.next_element = None
return result
def hasNext(self):
while self.stack:
try:
current = next(self.stack[-1])
except StopIteration:
self.stack.pop()
continue
if current.isInteger():
self.next_element = current.getInteger()
return True
else:
self.stack.append(iter(current.getList()))
return False
__init__
): O(1)
next
): O(1) on average
hasNext
guarantees that next
will simply return the next integer.hasNext
): O(1) on average for each element
Thus, the amortized time complexity for both next
and hasNext
is O(1) per call.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?