Problem Description
Implement an iterator over a nested list of integers where each element could be an integer or a list of integers (nested arbitrarily). The iterator should support two methods: next(), which returns the next integer, and hasNext(), which checks if there are any more integers to iterate over. The goal is to flatten the nested structure such that successive calls to next() yield the integers in their original order.
Key Insights
- Use a stack to manage the nested elements; pushing items in reverse order maintains the correct processing sequence.
- In the hasNext() method, perform a lazy flattening by processing nested lists only as needed.
- The iterator ensures that when next() is called, the top of the stack is always an integer.
- The space complexity is linear in the total number of elements due to the auxiliary stack.
Space and Time Complexity
Time Complexity: O(n) in the worst case, where n is the total number of integers, as each element is processed once. Space Complexity: O(n) due to the use of the stack to manage the nested elements.
Solution
The solution uses a stack to store the NestedInteger elements in a reversed order. When hasNext() is invoked, the algorithm checks the top element of the stack:
- If it is an integer, we are ready to call next().
- If it is a list, pop it from the stack and push its elements (also in reverse order) back onto the stack. This lazy processing ensures that we flatten the nested structure on the fly and maintain O(n) time and space complexity.
Code Solutions
Below are the implementations in Python, JavaScript, C++, and Java.