Python solution with detailed explanation

  • 0


    Flatten Nested List Iterator

    • We maintain a stack st which has a tuple as (lst, idx).
    • The invariant we maintain here is that top of the stack has lst, idx such that lst[idx] is the next interger. Therefore we need some initialization (prior) to first call to next() and then we need some work to maintain the invariant after a call to every next().
    • next() - returns the interger pointed by top of stack.
    • Look at the code for more details.
    class NestedIterator(object):
        def __init__(self, nestedList):
            Initialize your data structure here.
            :type nestedList: List[NestedInteger]
   = [[nestedList, 0]]
        def arrange(self):
                lst, idx =[-1][0],[-1][1]
                if len(lst) == idx:
                elif lst[idx].isInteger() == False:
          [-1][1] += 1 # Important - move the current list index before pushing the new list.
          [lst[idx].getList(), 0])
        def next(self):
            :rtype: int
            lst, idx =[-1][0],[-1][1]
            result = lst[idx].getInteger()
  [-1][1] += 1
            return result
        def hasNext(self):
            :rtype: bool
            return bool(len(

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.