341. Flatten Nested List Iterator
Stack, Tree, DFS, Design, Queue, Iterator, AMateList ·Problem Statement
link: LeetCode.cn LeetCode You are given a nested list of integers nestedList. 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
initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res If res matches the expected flattened list, then your code will be judged as correct.
Example:
Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Constraints: 1 <= nestedList.length <= 500 The values of the integers in the nested list is in the range [-106, 106].
Solution Approach
The solution involves using a stack to iteratively flatten the nested list, ensuring that all nested lists are fully expanded before retrieving the next integer.
Algorithm
- Initialize a stack with the reversed nested list to maintain the order of elements for processing.
- Iteratively check the top element of the stack: if it’s a list, expand it by adding its elements back to the stack in reverse order; if it’s an integer, keep it ready for retrieval.
- Pop and return the integer from the stack when next() is called, and continue flattening the nested lists until all elements are processed.
Implement
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.stack = nestedList[::-1]
def next(self) -> int:
return self.stack.pop(-1).getInteger()
def hasNext(self) -> bool:
while len(self.stack) > 0 and self.stack[-1].isInteger() is False:
self.stack += self.stack.pop().getList()[::-1]
return len(self.stack) > 0