> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Flatten Nested List Iterator Python Solution

> Tested Python solution for LeetCode 341 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 341, [Medium](/catalog/medium). Topics: [Stack](/catalog/topics/stack), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Design](/catalog/topics/design), [Queue](/catalog/topics/queue), Iterator. [View on LeetCode](https://leetcode.com/problems/flatten-nested-list-iterator/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 341   # by problem number
lcpy gen -s flatten_nested_list_iterator   # by problem name
```

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

### Examples

```
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].
```

```
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 \[-10\<sup>6\</sup>, 10\<sup>6\</sup>].

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/flatten_nested_list_iterator/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/flatten_nested_list_iterator/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from typing import Any


class NestedIterator:
    # Time: O(n) init + amortized O(1) per call  # n = total integers
    # Space: O(n)
    def __init__(self, nested_list: list[Any]) -> None:
        self._values: list[int] = []
        stack: list[Any] = list(reversed(nested_list))
        while stack:
            item = stack.pop()
            if isinstance(item, int):
                self._values.append(item)
            else:
                stack.extend(reversed(item))
        self._index = 0

    def next(self) -> int:
        value = self._values[self._index]
        self._index += 1
        return value

    def has_next(self) -> bool:
        return self._index < len(self._values)
```

## Complexity

| Time | Space |
| - | - |
| O(n) init + amortized O(1) per call  # n = total integers | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.