Skip to main content
LeetCode 341, Medium. Topics: Stack, Tree, Depth-First Search, Design, Queue, Iterator. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 14 parametrized pytest cases, and a playground notebook:

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:
If res matches the expected flattened list, then your code will be judged as correct.

Examples

Constraints

  • 1 <= nestedList.length <= 500
  • The values of the integers in the nested list is in the range [-10<sup>6</sup>, 10<sup>6</sup>].

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026