Flatten Nested List Iterator — LeetCode 341 Python Solution

MediumStackTreeDepth-First SearchDesignQueueIterator
Problem
#341
Pattern
Stack
Reading time
8 min

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.

Example

initialize iterator with nestedList
res = []
while iterator.hasNext()
    append iterator.next() to the end of res
return res

Python solution

Python
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger:
#    def isInteger(self) -> bool:
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        """
#
#    def getInteger(self) -> int:
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        """
#
#    def getList(self) -> [NestedInteger]:
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        """


class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        def dfs(ls):
            for x in ls:
                if x.isInteger():
                    self.nums.append(x.getInteger())
                else:
                    dfs(x.getList())

        self.nums = []
        self.i = -1
        dfs(nestedList)

    def next(self) -> int:
        self.i += 1
        return self.nums[self.i]

    def hasNext(self) -> bool:
        return self.i + 1 < len(self.nums)


# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 341. Flatten Nested List Iterator is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack and Queue.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 341. Flatten Nested List Iterator?
LeetCode 341. Flatten Nested List Iterator is rated Medium on LeetCode.
What is the time complexity of LeetCode 341. Flatten Nested List Iterator?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 341. Flatten Nested List Iterator?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 341. Flatten Nested List Iterator cover?
LeetCode 341. Flatten Nested List Iterator is tagged Stack, Tree, Depth-First Search, Design, Queue and Iterator on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview