Flatten Nested List Iterator

Medium Topics Company Tags

Implement NestedIterator for a nested list whose entries are integers or other nested lists. Return the integers in their original left-to-right order, visiting every inner list before continuing after it.

  • NestedIterator(nestedList) initializes the iterator.
  • hasNext() reports whether an integer remains. Calling it repeatedly must not consume an integer.
  • next() returns the next integer and advances the iterator. It is called only when an integer remains.

The judge constructs your iterator, calls next() while hasNext() is true, and compares the collected integers with the output array. Empty inner lists contribute no values. The provided NestedInteger interface has isInteger(), getInteger(), and getList() methods. Go and C# capitalize these method names. In Rust, match NestedInteger::Int(value) or NestedInteger::List(items). Do not implement NestedInteger yourself.

Example 1:

Input: nestedList = [[2,[]],[-1,[5]],3]

Output: [2,-1,5,3]

Explanation: The first inner list contributes 2. The second contributes -1 followed by 5, and the final outer entry contributes 3. The empty list contributes nothing.

Example 2:

Input: nestedList = [[],[[]],[]]

Output: []

Explanation: Every entry is an empty list or contains only empty lists. hasNext returns false without any next call, so the output is empty.

Example 3:

Input: nestedList = [[0,[-2]],[],[4]]

Output: [0,-2,4]

Explanation: Reading from left to right returns 0, then -2 from the deeper list, and finally 4. The empty list in between is skipped.

Constraints:

  • 1 <= nestedList.length <= 500
  • Every integer is between -1000000 and 1000000, inclusive.
  • Each entry is an integer or a nested list, which may be empty.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.