Skip to content

Commit c4ef051

Browse files
committed
O(n) time and O(n) space using Stack.
1 parent 95a6cd7 commit c4ef051

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

341. Flatten Nested List Iterator/341. Flatten Nested List Iterator.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,13 @@
1616
Explanation: By calling next repeatedly until hasNext returns false,
1717
the order of elements returned by next should be: [1,4,6].
1818
"""
19+
20+
1921
# """
2022
# This is the interface that allows for creating nested lists.
2123
# You should not implement it, or speculate about its implementation
2224
# """
23-
#class NestedInteger:
25+
# class NestedInteger:
2426
# def isInteger(self) -> bool:
2527
# """
2628
# @return True if this NestedInteger holds a single integer, rather than a nested list.
@@ -40,20 +42,20 @@
4042

4143
class NestedIterator:
4244
def __init__(self, nestedList: [NestedInteger]):
43-
self.stack = nestedList[::-1]
44-
45-
45+
# Copy the list into stack
46+
47+
self.stack = nestedList[:]
48+
4649
def next(self) -> int:
47-
return self.stack.pop().getInteger()
48-
50+
return self.stack.pop(0)
51+
4952
def hasNext(self) -> bool:
53+
# We will check if there are values in the stack. If yes then we will first check if the first value is integer. Will add the values of a list into the stack otherwise.
5054
while self.stack:
51-
top = self.stack[-1]
52-
if top.isInteger():
53-
return True
54-
self.stack = self.stack[:-1] + top.getList()[::-1]
55+
if self.stack[0].isInteger():
56+
return True
57+
self.stack = self.stack[0].getList() + self.stack[1:]
5558
return False
56-
5759

5860
# Your NestedIterator object will be instantiated and called as such:
5961
# i, v = NestedIterator(nestedList), []

0 commit comments

Comments
 (0)