341.Flatten Nested List Iterator

Tags: [recursion], [flat], [data_structure], [flat_data_structure], [pre_processing], [stack]

Link: https://leetcode.com/problems/flatten-nested-list-iterator/#/description

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:
Given the list[[1,1],2,[1,1]],

By calling next repeatedly until has Next returns false, the order of elements returned by next should be:[1,1,2,1,1].

Example 2:
Given the list[1,[4,[6]]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1,4,6].


Solution: Stack

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

class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.stack = []
        for i in xrange(len(nestedList) - 1, -1, -1):
            self.stack.append(nestedList[i])

    def next(self):
        """
        :rtype: int
        """
        return self.stack.pop()

    def hasNext(self):
        """
        :rtype: bool
        """
        while self.stack:
            curr = self.stack[-1]
            if curr.isInteger():
                return True

            curr = self.stack.pop()
            curr_list = curr.getList()
            for i in xrange(len(curr_list) - 1, -1, -1):
                self.stack.append(curr_list[i])

        return False

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

Revelation:

  • Using stack to flat the nested integer layer by layer.

Note:

  • Time complexity of initialization = O(n), n is the number of the given nested integers.
  • Time complexity of next = O(1).
  • Time complexity of hasNext = O(k + p), k is the max number of nested layer, p is the max number of nested integers inside of the kth layer.

Solution: recursion, pre_processing

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

class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.arr = self.flat_nested_list(nestedList)
        self.index = 0

    def flat_nested_list(self, nested_list):
        # base case
        if not nested_list:
            return []

        arr = []
        for elem in nested_list:
            if elem.isInteger():
                arr.append(elem.getInteger())
            else:
                arr += self.flat_nested_list(elem.getList())

        return arr

    def next(self):
        """
        :rtype: int
        """
        elem = self.arr[self.index]
        self.index += 1
        return elem

    def hasNext(self):
        """
        :rtype: bool
        """
        return len(self.arr) and self.index < len(self.arr)

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

Revelation:

  • For the iterator problem, we can first think do the pre processing.

Note:

  • Time complexity of initialize the obj = O(n), n is the number of integers in the given nested list.
  • Time complexity of "next" = O(1).
  • Time complexity of "hasNext" = O(1)

results matching ""

    No results matching ""