#341
Flatten Nested List Iterator
MediumStackTreeDepth-First SearchDesignQueueIteratorStackRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses an explicit stack to manage the nested structure without needing to create a separate flattened list upfront. This approach allows us to iterate through the elements as needed, maintaining a pointer to the current position.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a stack with the nested list.
- 2Step 2: While the stack is not empty, check the top element.
- 3Step 3: If the top element is an integer, return it. If it's a list, pop it and push its elements onto the stack.
solution.py16 lines
1# Full working Python code
2class NestedIterator:
3 def __init__(self, nestedList):
4 self.stack = list(reversed(nestedList))
5
6 def next(self):
7 return self.stack.pop().getInteger()
8
9 def hasNext(self):
10 while self.stack:
11 top = self.stack[-1]
12 if top.isInteger():
13 return True
14 self.stack.pop()
15 self.stack.extend(reversed(top.getList()))
16 return Falseℹ
Complexity note: The time complexity is O(n) because each element is processed once. The space complexity is O(n) due to the stack used to store elements during the flattening process.
- 1Understanding nested structures is crucial for this problem.
- 2Using a stack allows us to manage depth without recursion.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.