Grokking Tree Coding Patterns for Interviews
Vote

0% completed

​

All Paths for a Sum (medium)

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 3 years ago

If the tree is unbalanced, couldn't the space complexity still be O(N^2)? If the tree is balanced each path would have O(logN) nodes in the path but if its a linked list, it would have N nodes in the path.

A

Anonymous

· 3 years ago

allPaths.append(list(currentPath)) <- why do we add list() here?

Show 1 reply
A

Anonymous

· 4 years ago

What is the time complexity for the JS solution? Wouldn't it just be O(n) ?

Arrays dynamically resize in javascript unlike in Java, pushing and popping from the tail is O(1). The length of array can be modified at run time (when necessary).

Or am I offtrack?

Show 1 reply
A

Anonymous

· 4 years ago

So, time complexity is it O(N^2) or N(logN)?

Show 2 replies
A

Anonymous

· 4 years ago

Why do we need to cast the currentPath list to a list if it's already a list? If we don't cast it the list is empty for some reason.

Show 3 replies
A

Anonymous

· 4 years ago

Can you please explain this part?

remove the current node from the path to backtrack,

we need to remove the current node while we are going up the recursive call stack.

del currentPath[-1] Why do we need to remove the current node in the end?

Show 1 reply
A

Anonymous

· 4 years ago

I copy and pasted your solution in for "All Paths for a Sum" and the code below does not seem to work. It just outputs two empty arrays. Even using the Dequeue lib (which, seeing as I generally can't install libs during an interview, it feels odd to see these peppered in), it does not work. Anyone else seen this?

Show 5 replies
A

Anonymous

· 5 years ago

"The time complexity of the above algorithm is O(N^2), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once (which will take O(N)), and for every leaf node, we might have to store its path (by making a copy of the current path) which will take O(N)."

Can someone explain why storing its path will take O(N) time complexity instead of O(1)? I can understand O(N) space complexity, but why would the time to store an array be proportional to the size of it?

Show 2 replies
A

Anonymous

· 5 years ago

In the JS solution, what's the point of using deque? Wouldn't an array be fine here, since array push and pop are O(1) operations

Show 1 reply

Reading Progress

0%


Vote for new content