Skip to content

Commit 7641a77

Browse files
author
Partho Biswas
committed
341. Flatten Nested List Iterator
1 parent d4f5f17 commit 7641a77

File tree

3 files changed

+136
-0
lines changed

3 files changed

+136
-0
lines changed

README.md

100755100644
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ I have solved quite a number of problems from several topics. See the below tabl
250250
|05| [239. Sliding Window Maximum](https://tinyurl.com/rvhujl5)| [Python](https://tinyurl.com/wu6rdaw/239_Sliding_Window_Maximum.py)| **[Video 1](https://tinyurl.com/v767bl3)**, [Official](https://tinyurl.com/www4np2), [Art 1](https://tinyurl.com/y8nbroux), [Art 2](https://tinyurl.com/s62fzls), **[Art 3](https://tinyurl.com/vd3dtch)**, **[Art 4](https://tinyurl.com/yx3sjp46)** | Hard | 📌 Can be solved using Heap, Deque and DP |
251251
|06| [739. Daily Temperatures](https://tinyurl.com/ybbezzmt)| [Python](https://tinyurl.com/wu6rdaw/739_Daily_Temperatures.py)| **[Video 1](https://tinyurl.com/sdbkh3z)**, **[Video 2](https://tinyurl.com/rbvaozl)**, [Art 1](https://tinyurl.com/ss3d9tx) | Medium | 📌 TODO: Check again. A tricky one |
252252
|07| **[150. Evaluate Reverse Polish Notation](https://tinyurl.com/y2xrje8v)** | [Python](https://tinyurl.com/wu6rdaw/150_Evaluate_Reverse_Polish_Notation.py), [Swift](https://tinyurl.com/wuja3c4/150_Evaluate_Reverse_Polish_Notation.swift)| [Vid 1](https://tinyurl.com/s92fp4r) | Medium | --- |
253+
|08| **[341. Flatten Nested List Iterator](https://tinyurl.com/y6saxwjz)** | [Python](https://tinyurl.com/wu6rdaw/341_Flatten_Nested_List_Iterator.py), [Swift](https://tinyurl.com/wuja3c4/341_Flatten_Nested_List_Iterator.swift)| [Vid 1](https://tinyurl.com/vkj4qll), [Art 1](https://tinyurl.com/wnvvafx), [Art 2](https://tinyurl.com/wmrlxmz), [Art 3](https://tinyurl.com/uplntb3), **[Art 4](https://tinyurl.com/v3q9qfw)**, **[Art 5](https://tinyurl.com/rotxca8)** | Medium | TODO: Check again. Very Important. Learned new things |
253254

254255
</p>
255256
</details>
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
# """
2+
# This is the interface that allows for creating nested lists.
3+
# You should not implement it, or speculate about its implementation
4+
# """
5+
# class NestedInteger(object):
6+
# def isInteger(self):
7+
# """
8+
# @return True if this NestedInteger holds a single integer, rather than a nested list.
9+
# :rtype bool
10+
# """
11+
#
12+
# def getInteger(self):
13+
# """
14+
# @return the single integer that this NestedInteger holds, if it holds a single integer
15+
# Return None if this NestedInteger holds a nested list
16+
# :rtype int
17+
# """
18+
#
19+
# def getList(self):
20+
# """
21+
# @return the nested list that this NestedInteger holds, if it holds a nested list
22+
# Return None if this NestedInteger holds a single integer
23+
# :rtype List[NestedInteger]
24+
# """
25+
26+
27+
28+
from collections import deque
29+
# Approach 1: Brite force ut not good for the interview. This approach, modifies the input list
30+
class NestedIterator(object):
31+
32+
def __init__(self, nestedList):
33+
"""
34+
Initialize your data structure here.
35+
:type nestedList: List[NestedInteger]
36+
"""
37+
self.q = deque()
38+
self.flatten(nestedList)
39+
40+
def flatten(self, nestedList):
41+
for l in nestedList:
42+
if l.isInteger():
43+
self.q.append(l.getInteger())
44+
else:
45+
self.flatten(l.getList())
46+
47+
def next(self):
48+
"""
49+
:rtype: int
50+
"""
51+
return self.q.popleft()
52+
53+
def hasNext(self):
54+
"""
55+
:rtype: bool
56+
"""
57+
return len(self.q) > 0
58+
59+
60+
61+
62+
# Approach 2: This approach, doesn't modify the input list but depends on hasNext to be called, which is also not good and not the perfect implementation for the interview
63+
class NestedIterator:
64+
def __init__(self, nestedList: [NestedInteger]):
65+
print("nestedList: ", nestedList)
66+
self.__nestedList = nestedList
67+
self.__position = 0
68+
self.__lists = []
69+
70+
def next(self) -> int:
71+
integer = self.__nestedList[self.__position].getInteger()
72+
self.__position += 1
73+
print("------")
74+
print("integer: ", integer)
75+
print("self.__nestedList: ", self.__nestedList)
76+
print("self.__position: ", self.__position)
77+
print("self.__lists: ", self.__lists)
78+
return integer
79+
80+
def hasNext(self) -> bool:
81+
while not self.__isComplete():
82+
currNode = self.__nestedList[self.__position]
83+
84+
if currNode.isInteger():
85+
return True
86+
else:
87+
self.__position += 1
88+
self.__lists.append((self.__nestedList, self.__position))
89+
self.__position = 0
90+
self.__nestedList = currNode.getList()
91+
92+
if self.__isComplete() and not self.__listEmpty():
93+
self.__nestedList, self.__position = self.__lists.pop()
94+
return self.hasNext()
95+
96+
return False
97+
98+
def __listEmpty(self) -> bool:
99+
return len(self.__lists) == 0
100+
101+
def __isComplete(self) -> bool:
102+
return self.__position >= len(self.__nestedList)
103+
104+
105+
# https://tinyurl.com/rotxca8
106+
class NestedIterator(object):
107+
108+
def __init__(self, nestedList):
109+
self.nestedListStack = [[nestedList, 0]] # <list, next element index/position>
110+
111+
# Here, next method does't have any dependency over hasNext
112+
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()
120+
121+
def hasNext(self):
122+
currentNestedListStack = self.nestedListStack
123+
while currentNestedListStack:
124+
nestedList, position = currentNestedListStack[-1]
125+
if position == len(nestedList):
126+
currentNestedListStack.pop() # this nestedList is already processed, remove from stack
127+
else:
128+
currentItem = nestedList[position]
129+
if currentItem.isInteger():
130+
return True
131+
currentNestedListStack[-1][1] += 1 # incremets current nestedListStack index
132+
currentNestedListStack.append([currentItem.getList(), 0])
133+
return False
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import Foundation
2+

0 commit comments

Comments
 (0)