← Back to challenges

Flatten Nested List Iterator

PythonHardclassesconditionsdata_structures

Instructions

Implement a class iterator to flatten a nested list of lists of integers. Each list element is either an integer or a list. There can be many levels of nested lists in lists.

The class initializes with a nested list. It also has two methods:

  1. next() returns an integer in the order of appearance.
  2. hasNext() returns True / False regarding if all integers have been retrieved or not.

Write the Class implementation for three required methods.

Examples

ni, actual = NestedIterator([[1, 1], 2, [1, 1]]), []
while ni.hasNext():
    actual.append(ni.next())
actual ➞ [1, 1, 2, 1, 1]

ni, actual = NestedIterator([1, [4, [6]]]), []
while ni.hasNext():
    actual.append(ni.next())
actual ➞ [1, 4, 6]

ni, actual = NestedIterator([[[]], []]), []
while ni.hasNext():
    actual.append(ni.next())
actual ➞ []

Notes

N/A

python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.