Talentd
FleetCode
Make and follow sheets.Sign in

Flatten Nested List Iterator solution and explanation

MediumDepth-First SearchDesignIteratorQueue6 min read65.6% acceptanceUpdated 9 Apr 2026
Flatten Nested List Iterator - Leetcode 341 - PythonNeetCodeIO · 10:14 · 16K viewsWatch on YouTube
9 more videos on this problem
  1. Flatten Nested List Iterator - Leetcode 341 - PythonNeetCodeIO · 10:14 · 16K views
  2. Flatten Nested List Iterator | Live Coding with Explanation | Leetcode - 341Algorithms Made Easy · 8:14 · 13K views
  3. 341. Flatten Nested List Iterator using C++. (Full Solution).Sahil Saluja · 8:18 · 1K views
  4. FLATTEN NESTED LIST ITERATOR | LEETCODE 341 | PYTHON DFS SOLUTIONCracking FAANG · 12:01 · 1K views
  5. Flattened Nested List | Leetcode 341Coding Decoded · 8:54 · 1K views
  6. Flatten Nested List Iterator | Leetcode 341 | Montonic Stacks | Live coding sessionCoding Decoded · 0:54 · 1K views
  7. Flatten Nested List Iterator | Решение на Python | LeetCode 341Сурен Хоренян · 20:59 · 691 views
  8. Flatten Nested List Iterator | Leetcode 341 | Stack | Iterator | MediumNitesh Nanda · 12:21 · 488 views
  9. Leetcode 341: Flatten Nested List IteratorAlgorithms Casts · 23:53 · 274 views
  10. LeetCode 341: Flatten Nested List IteratorKevin Dai · 3:01 · 215 views

The 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.

Implement the NestedIterator class:

  • NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
  • int next() Returns the next integer in the nested list.
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

Your code will be tested with the following 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, then your code will be judged as correct.

Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:

Input: nestedList = [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

Constraints:

  • 1 <= nestedList.length <= 500
  • The values of the integers in the nested list is in the range [-106, 106].

Approach overview

Problem Overview: You receive a list where each element is either an integer or another nested list. The task is to design an iterator that returns all integers in a flattened order. Calls to next() should return the next integer, and hasNext() should indicate whether more integers remain.

The challenge is not just flattening the list, but designing an iterator interface that efficiently processes nested structures. The structure behaves like a tree where lists are internal nodes and integers are leaf nodes. Traversing it requires techniques similar to Depth-First Search.

Approach 1: Recursive Flattening (O(n) time, O(n) space)

This approach performs a full depth-first traversal of the nested structure during initialization. Each element is inspected: if it is an integer, append it to a result list; if it is another list, recursively flatten it. After this preprocessing step, the iterator simply walks through the flattened array using an index pointer. next() returns the current element and increments the pointer, while hasNext() checks whether the pointer is still within bounds. The key idea is trading memory for simplicity by precomputing the entire flattened sequence. This solution uses recursion and mirrors standard DFS traversal patterns.

Approach 2: Using Stack for Iterative Flattening (O(n) time, O(d) space)

This approach avoids flattening everything upfront and instead processes the structure lazily using a stack. Push all elements of the nested list onto the stack in reverse order. During hasNext(), check the top element: if it is an integer, return true; if it is a list, pop it and push its contents back onto the stack in reverse order. This ensures the next element processed matches the correct traversal order. The stack simulates recursion and effectively performs an iterative DFS. Space usage depends on the maximum nesting depth d rather than the total number of integers.

This method aligns closely with how iterators are typically implemented in system design problems. Instead of storing all values, it maintains traversal state dynamically. The logic resembles how an iterator walks through a complex structure while exposing a simple interface.

Recommended for interviews: The stack-based iterator approach is usually preferred. Recursive flattening demonstrates understanding of DFS, but it eagerly stores all integers and uses extra memory. The stack solution keeps the iterator lazy and processes elements only when needed, which better matches real-world iterator design patterns.

Approach 1: Approach 1: Recursive Flattening

This approach utilizes recursion to flatten the nested list. The idea is to traverse each element in the nested list. If the element is an integer, it gets added to a result list. If it's a list, the function calls itself recursively to add its flattened elements to the result list.

class NestedIterator:
    def __init__(self, nestedList):
        self.flatList = []
        self.index = -1
        self.flatten(nestedList)

    def flatten(self, nestedList):
        for element in nestedList:
            if element.isInteger():
                self.flatList.append(element.getInteger())
            else:
                self.flatten(element.getList())

    def next(self):
        self.index += 1
        return self.flatList[self.index]

    def hasNext(self):
        return self.index + 1 < len(self.flatList)
public class NestedIterator implements Iterator<Integer> {
    private List<Integer> flatList;
    private int index;

    public NestedIterator(List<NestedInteger> nestedList) {
        flatList = new ArrayList<>();
        index = 0;
        flatten(nestedList);
    }

    private void flatten(List<NestedInteger> nestedList) {
        for (NestedInteger element : nestedList) {
            if (element.isInteger()) {
                flatList.add(element.getInteger());
            } else {
                flatten(element.getList());
            }
        }
    }

    public Integer next() {
        return flatList.get(index++);
    }

    public boolean hasNext() {
        return index < flatList.size();
    }
}

The constructor initializes the object with a flattened list and an iterator index. The `flatten` method is a helper function that recursively adds elements to `flatList`. The `next` method returns the next element from `flatList`, while `hasNext` checks the bounds.

Complexity

Time Complexity: O(N), where N is the total number of integers in the nested list. Space Complexity: O(N) for the flattened list storage.

Try this approach in the editor

Approach 2: Approach 2: Using Stack for Iterative Flattening

This approach uses a stack to iterate over the nested list in a depth-first manner. This helps simulate recursive behavior iteratively, thus allowing the use of iterator pattern directly without full pre-flattening.

class NestedIterator {
    constructor(nestedList) {
        this.stack = [];
        this._flatten(nestedList);
    }
    
    _flatten(nestedList) {
        for (let i = nestedList.length - 1; i >= 0; i--) {
            this.stack.push(nestedList[i]);
        }
    }
    
    hasNext() {
        while (this.stack.length) {
            let top = this.stack.pop();
            if (top.isInteger()) {
                this.stack.push(top);
                return true;
            }
            this._flatten(top.getList());
        }
        return false;
    }
    
    next() {
        return this.stack.pop().getInteger();
    }
}
public class NestedIterator {
    private Stack<NestedInteger> stack = new Stack<NestedInteger>();

    public NestedIterator(IList<NestedInteger> nestedList) {
        Flatten(nestedList);
    }

    private void Flatten(IList<NestedInteger> nestedList) {
        for (int i = nestedList.Count - 1; i >= 0; i--) {
            stack.Push(nestedList[i]);
        }
    }

    public bool HasNext() {
        while (stack.Count > 0) {
            NestedInteger top = stack.Pop();
            if (top.IsInteger()) {
                stack.Push(top);
                return true;
            }
            Flatten(top.GetList());
        }
        return false;
    }

    public int Next() {
        return stack.Pop().GetInteger();
    }
}

The implementation utilizes a stack to simulate recursive traversal. The stack is populated in reverse order to ensure elements are visited in correct sequence. The `hasNext` method ensures the top of the stack is an integer before processing.

Complexity

Time Complexity: Amortized O(1) per call for `next` and `hasNext` due to efficient stack management. Space Complexity: O(N), where N is the total number of integers stored in the stack during traversal.

Try this approach in the editor

Approach 3: Default Approach

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *   public:
 *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     bool isInteger() const;
 *
 *     // Return the single integer that this NestedInteger holds, if it holds a single integer
 *     // The result is undefined if this NestedInteger holds a nested list
 *     int getInteger() const;
 *
 *     // Return the nested list that this NestedInteger holds, if it holds a nested list
 *     // The result is undefined if this NestedInteger holds a single integer
 *     const vector<NestedInteger> &getList() const;
 * };
 */

class NestedIterator {
public:
    NestedIterator(vector<NestedInteger>& nestedList) {
        auto dfs = [&](this auto&& dfs, vector<NestedInteger>& ls) -> void {
            for (auto& x : ls) {
                if (x.isInteger()) {
                    nums.push_back(x.getInteger());
                } else {
                    dfs(x.getList());
                }
            }
        };
        dfs(nestedList);
    }

    int next() {
        return nums[++i];
    }

    bool hasNext() {
        return i + 1 < nums.size();
    }

private:
    vector<int> nums;
    int i = -1;
};

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i(nestedList);
 * while (i.hasNext()) cout << i.next();
 */
/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *     If value is provided, then it holds a single integer
 *     Otherwise it holds an empty nested list
 *     constructor(value?: number) {
 *         ...
 *     };
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     isInteger(): boolean {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     getInteger(): number | null {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     setInteger(value: number) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     add(elem: NestedInteger) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds,
 *     or an empty list if this NestedInteger holds a single integer
 *     getList(): NestedInteger[] {
 *         ...
 *     };
 * };
 */

class NestedIterator {
    private nums: number[] = [];
    private i = -1;
    constructor(nestedList: NestedInteger[]) {
        const dfs = (ls: NestedInteger[]) => {
            for (const x of ls) {
                if (x.isInteger()) {
                    this.nums.push(x.getInteger());
                } else {
                    dfs(x.getList());
                }
            }
        };
        dfs(nestedList);
    }

    hasNext(): boolean {
        return this.i + 1 < this.nums.length;
    }

    next(): number {
        return this.nums[++this.i];
    }
}

/**
 * Your ParkingSystem object will be instantiated and called as such:
 * var obj = new NestedIterator(nestedList)
 * var a: number[] = []
 * while (obj.hasNext()) a.push(obj.next());
 */
/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * type NestedInteger struct {
 * }
 *
 * // Return true if this NestedInteger holds a single integer, rather than a nested list.
 * func (this NestedInteger) IsInteger() bool {}
 *
 * // Return the single integer that this NestedInteger holds, if it holds a single integer
 * // The result is undefined if this NestedInteger holds a nested list
 * // So before calling this method, you should have a check
 * func (this NestedInteger) GetInteger() int {}
 *
 * // Set this NestedInteger to hold a single integer.
 * func (n *NestedInteger) SetInteger(value int) {}
 *
 * // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 * func (this *NestedInteger) Add(elem NestedInteger) {}
 *
 * // Return the nested list that this NestedInteger holds, if it holds a nested list
 * // The list length is zero if this NestedInteger holds a single integer
 * // You can access NestedInteger's List element directly if you want to modify it
 * func (this NestedInteger) GetList() []*NestedInteger {}
 */

type NestedIterator struct {
	nums []int
	i    int
}

func Constructor(nestedList []*NestedInteger) *NestedIterator {
	var dfs func([]*NestedInteger)
	nums := []int{}
	i := -1
	dfs = func(ls []*NestedInteger) {
		for _, x := range ls {
			if x.IsInteger() {
				nums = append(nums, x.GetInteger())
			} else {
				dfs(x.GetList())
			}
		}
	}
	dfs(nestedList)
	return &NestedIterator{nums, i}
}

func (this *NestedIterator) Next() int {
	this.i++
	return this.nums[this.i]
}

func (this *NestedIterator) HasNext() bool {
	return this.i+1 < len(this.nums)
}
// #[derive(Debug, PartialEq, Eq)]
// pub enum NestedInteger {
//   Int(i32),
//   List(Vec<NestedInteger>)
// }
struct NestedIterator {
    nums: Vec<i32>,
    i: usize,
}

/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl NestedIterator {
    fn new(nested_list: Vec<NestedInteger>) -> Self {
        let mut nums = Vec::new();
        Self::dfs(&nested_list, &mut nums);
        NestedIterator { nums, i: 0 }
    }

    fn next(&mut self) -> i32 {
        let result = self.nums[self.i];
        self.i += 1;
        result
    }

    fn has_next(&self) -> bool {
        self.i < self.nums.len()
    }

    fn dfs(nested_list: &Vec<NestedInteger>, nums: &mut Vec<i32>) {
        for ni in nested_list {
            match ni {
                NestedInteger::Int(x) => nums.push(*x),
                NestedInteger::List(list) => Self::dfs(list, nums),
            }
        }
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Recursive Flattening

Time Complexity: O(N), where N is the total number of integers in the nested list. Space Complexity: O(N) for the flattened list storage.

Approach 2: Using Stack for Iterative Flattening

Time Complexity: Amortized O(1) per call for `next` and `hasNext` due to efficient stack management. Space Complexity: O(N), where N is the total number of integers stored in the stack during traversal.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Recursive FlatteningO(n)O(n)When simplicity matters and precomputing the entire flattened list is acceptable.
Stack-Based Iterative IteratorO(n)O(d)Preferred for interviews and production-style iterator design with lazy evaluation.

Frequently asked questions

Is Flatten Nested List Iterator easy or hard?

Flatten Nested List Iterator is considered a Medium difficulty problem. The traversal logic itself is straightforward, but designing a lazy iterator that correctly handles nested lists requires careful stack management.

Flatten Nested List Iterator Python/Java solution

Python and Java solutions typically implement a NestedIterator class with next() and hasNext() methods. The recursive solution flattens the list during initialization, while the optimal solution maintains a stack that expands nested lists during iteration.

How to solve Flatten Nested List Iterator in O(n)?

Traverse the nested structure using depth-first traversal. Either recursively flatten all integers into an array first, or maintain a stack that expands nested lists dynamically. Each integer is visited once, giving O(n) total time complexity.

What is the best approach for Flatten Nested List Iterator?

The stack-based iterative iterator is generally the best approach. It processes nested lists lazily using a stack and expands lists only when needed during hasNext(). This keeps time complexity O(n) while using O(d) space where d is the nesting depth.

Is Flatten Nested List Iterator asked at Google/Amazon/Meta?

Flatten Nested List Iterator has appeared in interviews at large tech companies including Google, Amazon, and Meta. It tests iterator design, stack usage, and depth-first traversal of nested structures.

What data structure is used in Flatten Nested List Iterator?

The most common data structure used is a stack to simulate depth-first traversal iteratively. Some solutions also rely on recursion, which implicitly uses the call stack. The problem also emphasizes iterator design patterns.

What is the time complexity of Flatten Nested List Iterator?

Both common approaches run in O(n) time, where n is the total number of integers across all nested lists. Each element is processed once either during recursive flattening or while being expanded from the stack during iteration.

Comments

Now write it yourselfClose this page and solve Flatten Nested List Iterator in the editor, without looking.
Practise Flatten Nested List Iterator