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 INPUT nestedList = [[1,1],2,[1,1]] [ ] [1, 1] 2 [1,1] 1 1 1 1 Iterator Methods: NestedIterator(nestedList) next() / hasNext() Depth: 0 to 2 levels Mixed integers + lists ALGORITHM STEPS 1 Initialize Stack Push all elements in reverse [1,1] (top) 2 [1,1] 2 hasNext() Check Flatten top if it's a list Until integer on top 3 next() Return Pop and return top int 4 Repeat Process Continue until stack empty Stack Operations: pop [1,1] push 1, 1 (reversed) pop 1 --> return Time: O(N) | Space: O(D) N = total elements, D = max depth FINAL RESULT Flattened Output Sequence: 1 1 2 1 1 0 1 2 3 4 [1, 1, 2, 1, 1] Iterator Call Sequence: hasNext() --> true next() --> 1 hasNext() --> true next() --> 1 next() --> 2 next() --> 1, next() --> 1 hasNext() --> false OK - Flattened! Key Insight: Use a stack to lazily flatten nested elements. When hasNext() is called, keep expanding the top element if it's a list (push children in reverse order) until an integer is on top. This ensures O(1) amortized operations and handles arbitrary nesting depths efficiently without pre-flattening the entire structure. TutorialsPoint - Flatten Nested List Iterator | Optimal Stack-Based Approach
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