Flatten Nested List Iterator - Leetcode 341 - Python

preview_player
Показать описание


0:00 - Read the problem
0:30 - Drawing Explanation
4:40 - Coding Explanation

leetcode 341

#neetcode #leetcode #python
Рекомендации по теме
Комментарии
Автор

This is a brute force solution. Image the interviewer telling you to make the constructor O(1). Now you have to think outside of the box.

msugal
Автор

One of those DSA questions that has actually come to use to me in production code. Although not for flattening an array but to replace each data structure in the array with another.

ngneerin
Автор

Quick question here: Why don't we use a queue? Won't it be more intuitive?

aswqe
Автор

Thanks. You're basically flattening the list in constructor (O(N)) and popping the stack afterwards. It's likely that in an inteview setting there might be a follow-up like: "make it lazy", "can you do it with less average memory consumption?"

Another way is to use generators and yield values or generators of values for lists. Or make hasNext to form a stack with DFS but one "top level" item at a time.

JMKAKAN
Автор

Do you think it would be more efficient if instead of having a stack list, reverse and pop, you use a stack deque and popleft?

dantonddsa
Автор

We probably would need something that wouldnt flatten the entire list in the constructor, any thoughts/suggestions on a solution which is more efficient?

srishtiganjoo
Автор

Thanks for the intitution Neetcode. i just wanted to ask that in flattening questions do we generally use recursion and stack?

abhinavnarula
Автор

question, what makes you use python versus other languages?

michaell
Автор

If we flatten the list in the __init__ method, how do we handle the case where data in the Iterator keeps changing?

ajaykumargogineni
Автор

Hey there! Thank you for the video. I came to the "pre-unpack" solution too (with deque), but I was wondering if there's another way to solve the problem, because unpacking takes O(n) in memory.
I came up to this solution with generators, I can't post github link here because youtube deletes my comment, so I'll try to paste my code here. Is this solution M: O(1) because we don't create a new collection, or is it M: O(n) because we add layers to the call stack? Thanks!

```
class NestedIterator:
def __init__(self, nestedList: list[NestedInteger]):
self.iter = self.iterate(nestedList, top_level=True)
self.next_value = next(self.iter)

def iterate(self, nested_list: list[NestedInteger], top_level: bool = False):
for nested_elem in nested_list:
if nested_elem.isInteger():
yield nested_elem.getInteger()
else:
yield from

if top_level:
yield None

def next(self) -> int:
ret_val = self.next_value
self.next_value = next(self.iter)
return ret_val

def hasNext(self) -> bool:
return self.next_value is not None
```

SurenKhorenyan
Автор

When does this "self.stack.reverse()" get triggered? Everytime after dfs() functin got called?

yizhang