Leetcode #341: Flatten Nested List Iterator
In this guide, we solve Leetcode #341 Flatten Nested List Iterator in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Stack, Tree, Depth-First Search, Design, Queue, Iterator
Intuition
The problem has a natural nested or last-in-first-out structure.
A stack lets us resolve matches in the correct order as we scan.
Approach
Push items as they appear and pop when you can finalize a decision.
The stack captures the unresolved part of the input.
Steps:
- Push elements as you scan.
- Pop when a rule or match is satisfied.
- Use the stack to compute results.
Example
initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res
Python Solution
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# """
#
# def getInteger(self) -> int:
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# """
#
# def getList(self) -> [NestedInteger]:
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
def dfs(ls):
for x in ls:
if x.isInteger():
self.nums.append(x.getInteger())
else:
dfs(x.getList())
self.nums = []
self.i = -1
dfs(nestedList)
def next(self) -> int:
self.i += 1
return self.nums[self.i]
def hasNext(self) -> bool:
return self.i + 1 < len(self.nums)
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
Complexity
The time complexity is O(n). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.