Flatten Nested List Iterator - Problem
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. Your iterator class NestedIterator should have:
NestedIterator(List<NestedInteger> nestedList)- Initializes the iterator with the nested listint next()- Returns the next integer in the nested listboolean hasNext()- Returnstrueif there are still some integers in the nested list
Your code will be tested with the pseudocode:
initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return resIf res matches the expected flattened list, your code is correct.
Input & Output
Example 1 — Nested Lists with Integers
$
Input:
nestedList = [[1,1],2,[1,1]]
›
Output:
[1,1,2,1,1]
💡 Note:
First sublist [1,1] gives 1,1. Then integer 2. Finally sublist [1,1] gives 1,1. Result: [1,1,2,1,1]
Example 2 — Deeply Nested Structure
$
Input:
nestedList = [1,[4,[6]]]
›
Output:
[1,4,6]
💡 Note:
First element is 1. Second element [4,[6]] contains 4 and nested [6] which contains 6. Result: [1,4,6]
Example 3 — Empty Lists
$
Input:
nestedList = [1,2,[],3]
›
Output:
[1,2,3]
💡 Note:
Process 1, then 2, skip empty list [], then 3. Result: [1,2,3]
Constraints
- 1 ≤ nestedList.length ≤ 500
- The values of the integers in the nested list is in the range [-106, 106]
Visualization
Tap to expand
Understanding the Visualization
1
Input
Nested list with mixed integers and sublists
2
Iterator
Process elements in order, expanding lists as needed
3
Output
Flat sequence of all integers
Key Takeaway
🎯 Key Insight: Use a stack to handle nested structures efficiently, expanding lists only when needed for optimal memory usage
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code