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 list
  • int next() - Returns the next integer in the nested list
  • boolean hasNext() - Returns true if 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 res

If 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
Flatten Nested List Iterator: [[1,1],2,[1,1]] → [1,1,2,1,1]Input: Nested Structure[1,1]2[1,1]Iterator ProcessingOutput: Flattened Sequence11211[1,1,2,1,1]hasNext() → true
next() → 1hasNext() → true
next() → 1
hasNext() → true
next() → 2
Iterator calls: hasNext(), next(), hasNext(), next(), ...
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
Asked in
Google 25 Facebook 20 Amazon 15 Microsoft 12
89.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen