Skip to content

Commit bc93c6a

Browse files
author
Partho Biswas
committed
no message
1 parent e96b707 commit bc93c6a

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

leetcode.com/python/341_Flatten_Nested_List_Iterator.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -102,32 +102,37 @@ def __isComplete(self) -> bool:
102102
return self.__position >= len(self.__nestedList)
103103

104104

105+
106+
# Most optimal and preferd approach
105107
# https://tinyurl.com/rotxca8
108+
# Debug the code to get a clear idea
106109
class NestedIterator(object):
107110

108111
def __init__(self, nestedList):
109-
self.nestedListStack = [[nestedList, 0]] # <list, next element index/position>
112+
self.nestedListStack = [[nestedList, 0]] # <list, current element index/position on the nested list>
110113

111114
# Here, next method does't have any dependency over hasNext
112115
def next(self):
113-
# print("------")
114-
# print("1 self.nestedListStack: ", self.nestedListStack)
115-
self.hasNext()
116-
# print("2 self.nestedListStack: ", self.nestedListStack)
117-
nestedList, position = self.nestedListStack[-1]
118-
self.nestedListStack[-1][1] += 1
119-
return nestedList[position].getInteger()
116+
currentNestedListStack = self.nestedListStack
117+
nestedList, currentPositionIdx = currentNestedListStack[-1]
118+
currentNestedListStack[-1][
119+
1] += 1 # updating currentPositionIdx by 1, since we are sending the current integer here, on next line
120+
return nestedList[currentPositionIdx].getInteger()
120121

121122
def hasNext(self):
122123
currentNestedListStack = self.nestedListStack
123124
while currentNestedListStack:
124-
nestedList, position = currentNestedListStack[-1]
125-
if position == len(nestedList):
126-
currentNestedListStack.pop() # this nestedList is already processed, remove from stack
125+
nestedList, currentPositionIdx = currentNestedListStack[-1]
126+
if currentPositionIdx == len(nestedList): # we are done with this nested list, let's pop it out.
127+
currentNestedListStack.pop()
127128
else:
128-
currentItem = nestedList[position]
129+
currentItem = nestedList[currentPositionIdx]
129130
if currentItem.isInteger():
130131
return True
131132
currentNestedListStack[-1][1] += 1 # incremets current nestedListStack index
132133
currentNestedListStack.append([currentItem.getList(), 0])
133-
return False
134+
return False
135+
136+
# Your NestedIterator object will be instantiated and called as such:
137+
# i, v = NestedIterator(nestedList), []
138+
# while i.hasNext(): v.append(i.next())

0 commit comments

Comments
 (0)