Convert Sorted Array to Binary Search Tree - Leetcode 108 - Python

  Рет қаралды 83,653

NeetCode

NeetCode

Күн бұрын

Пікірлер: 72
@NeetCode
@NeetCode 3 жыл бұрын
Tree Question Playlist: kzbin.info/www/bejne/hZ-2n2WOerZng7s
@kairokabir9696
@kairokabir9696 3 жыл бұрын
instaBlaster...
@ax5344
@ax5344 3 жыл бұрын
You are the first teacher among what I've checked who actually explained why when left > right, we need to return null. Others just take it for granted or gloss it over! Base conditions and details are always the most challenging to beginners! Thank you!
@chuckle_pugz96
@chuckle_pugz96 Жыл бұрын
what are you doing now? Just curious cause I recently started coding.
@roshangeorge97
@roshangeorge97 Жыл бұрын
Yeah the only explanation i needed for like an hour.
@moulee007
@moulee007 Жыл бұрын
​@@chuckle_pugz96will ask the same question to you after 2 years
@sagivalia5041
@sagivalia5041 Жыл бұрын
It's really admirable how you are not taking it for granted and conclude the helper function explanation as a Binary Search technique and explain it fully
@niko-l-
@niko-l- 3 жыл бұрын
2AM and I'm here. Man, you’re the best in explanations. Keep it going
@NeetCode
@NeetCode 3 жыл бұрын
Haha, 12am over here. Thanks for the kind words!
@wt7658
@wt7658 3 жыл бұрын
Best explanation ever. I am new to coding and appreciate you explain from basics such as 'why the helper can access the nums' and 'call the function' etc. thanks very much!
@sf-spark129
@sf-spark129 2 жыл бұрын
This is such a good explanation but this solution will not convert the given array into BST of [0,-3,9,-10,null,5]. Not that it matters, but I was a bit confused at first because that was the BST I was expecting. Here is why: -> Pointer input given:(0, 4) m = (0+4) //2 = 2 root = TreeNode(nums[2]) = 0 -> r.left = helper(0, 2-1=1) Pointer input given:(0, 1) m = (0+1) //2 = 0 root = TreeNode(nums[0]) = -10 -> r.left = helper(0, 0-1=-1), base-case met (L > R), return None -> r.right = helper(0+1=1, 1) Pointer input given:(1, 1) m = (1+1) //2 = 1 root = TreeNode(nums[1]) = -3 -> r.left = helper(1, 1-1=0), base-case met (L > R), return None -> r.right = helper(1+1=2, 1), base-case met (L > R), return None ... The final BST will look like [0,-10,5,null,-3,null,9] Easy fix or update to give you BST of [0,-3,9,-10,null,5] is actually to use math.ceil() rather than integer division here. It forces to round up. math.ceil((left + right) / 2)
@souravchavan7730
@souravchavan7730 2 жыл бұрын
Thank you. Had a same doubt.
@jointcc2
@jointcc2 Жыл бұрын
Thanks. This has cleared my doubt.
@ewanowacka4772
@ewanowacka4772 8 ай бұрын
I was thinking the same and implemented with m = (r+l)//2+1
@alexandremarangonicosta
@alexandremarangonicosta Ай бұрын
Space complexity is actually O(n) too because you create a TreeNode for each elem of the array.
@mmc64
@mmc64 Жыл бұрын
Your explanation is succinct and straight forward. When I tried this problem originally there was an extremely long and convoluted explanation about unique solutions etc... and different potential strategies. I spent days reading the article and trying to find anywhere else on the internet where someone uses the same terms they used to explain the problem but couldn't find it. Thanks for posting such a useful video.
@balaganesh5484
@balaganesh5484 2 жыл бұрын
Time and memory complexity is O(n) my guess, we are traversing every input and we are creating node for every input.
@jetunpatel-zw6tm
@jetunpatel-zw6tm Жыл бұрын
That is for the worst case where you know that the tree is not balanced and skewed. In that case you linearly traverse across all nodes, correct me if I am wrong.
@PorkBoy69
@PorkBoy69 6 ай бұрын
@@jetunpatel-zw6tm It is worst case (which is exactly what O notation is) but it is also every single case. You cannot add a node with visiting it. So your understanding doesn't really make sense.
@xjlonelystar
@xjlonelystar 2 жыл бұрын
god, i appreciate you always explain even the most basic things. Absolutely amazing!
@mohamedsalama2743
@mohamedsalama2743 8 ай бұрын
if you're confused why it doesn't matter to choose left or right when computing the mid for even numbers, it's because you can still build a binary search tree differently, so in case of -10, -3 will be on its right in that case and it will still work fine
@ranjitasahu19
@ranjitasahu19 5 ай бұрын
thank you so much, when you go by the code iteration the tree is forming with -10, -3 comes in right but in video its the other way so I was really confused.
@angelwidatti
@angelwidatti Жыл бұрын
I do not understand one thing: if the tree is balanced BST, then why and how the space complexity would be O(log n)?
@markomekjavic
@markomekjavic 2 жыл бұрын
This is such a good explanation - thank you for also explaning how nested functions/methods work:)
@NeetCode
@NeetCode 2 жыл бұрын
Glad it was helpful!
@tanmaysontakke1813
@tanmaysontakke1813 4 ай бұрын
for c++ users u have to add extra step if left == right otherwise it will be an infinite loop
@asmahamdym
@asmahamdym Жыл бұрын
after watching your explanation I really can't understand from anyone else, Please make more videos
@ruthylevi9804
@ruthylevi9804 3 жыл бұрын
this is the video that made it click! thank you for explaining the reasoning in necessary detail behind all this :)
@NeetCode
@NeetCode 3 жыл бұрын
Happy it was helpful!
@tabmax22
@tabmax22 2 жыл бұрын
Dude if I get into Google I'm genuinely donating 10% of my first pay cheque to you
@roshangeorge97
@roshangeorge97 Жыл бұрын
have you got in?
@jayjagtap7873
@jayjagtap7873 Жыл бұрын
This solution is genious
@geofox9484
@geofox9484 Жыл бұрын
Would this be wrong if I'm getting -10 and 5 as my 1st level after root?
@CST1992
@CST1992 7 ай бұрын
Memory complexity is still O(n) as you're creating n nodes. How is it O(log n)?
@danielsun716
@danielsun716 Жыл бұрын
if not nums: return None l, r = 0, len(nums) - 1 m = (l + r) // 2 root = TreeNode(nums[m]) root.left = self.sortedArrayToBST(nums[l: m]) root.right = self.sortedArrayToBST(nums[m + 1: r + 1]) return root
@KyuriousBot
@KyuriousBot 2 жыл бұрын
How are we making sure at every step that the subtress are height balanced? Can someone please explain?
@head0fmob
@head0fmob Жыл бұрын
you divide the list/ sublist by 2 (choosing the mid) each time you go to next tree level, so it will be automatically balance as dividing anything by 2 will give equal left and right sublist
@sushrutasengupta1273
@sushrutasengupta1273 11 ай бұрын
Can it be solved using two while loops seperately??
@DoJoStan
@DoJoStan 3 жыл бұрын
Amazing explanation.
@veliea5160
@veliea5160 2 жыл бұрын
in which case `l>r` "l" will be greater "r"
@Pranav-nn1lu
@Pranav-nn1lu 2 жыл бұрын
at line 16 and 17, because we are continously reducing the search space we will eventually reach a point where we cannot reduce it further and that's when 'l' will be greater than 'r'. You can test it out yourself by dry running the code :) I would recommend you to learn about binary search to understand this better.
@veliea5160
@veliea5160 2 жыл бұрын
@@Pranav-nn1lu ty. i figured that out after. when we calculate the first node in the last root.left, l=m=0 and since we pass `helper(l,m-1)`, m-1=-1 so r will be less than l
@lucy2003-d8p
@lucy2003-d8p Жыл бұрын
thank u fro the great explanation
@shooby117
@shooby117 3 жыл бұрын
Great explanations mate! :D
@NeetCode
@NeetCode 3 жыл бұрын
Thanks!
@sneezygibz6403
@sneezygibz6403 3 жыл бұрын
Thanks man
@bharatapar3937
@bharatapar3937 2 жыл бұрын
hi, I am getting the wrong output : [0,-3,5,null,null,-3,9,null,0,0,null,-3,null,-3,5,null,null,null,null,-3,null,null,0,-3] def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: def helper(l,r): if l>r: return None m = (l+r)//2 root = TreeNode(nums[m]) root.left = helper(1,m-1) root.right = helper(m+1,r) return root return helper(0,len(nums)-1) let me know what wrong i m doing ?
@ligrt2426
@ligrt2426 2 жыл бұрын
root.left = helper(l,m-1) change the 1 to l
@jobsearch9934
@jobsearch9934 2 жыл бұрын
Wouldn't space complexity still be O(n) since were creating "n" nodes?
@Maattttheww
@Maattttheww 2 жыл бұрын
Yep, I think that's a mistake.
@foudilbenouci482
@foudilbenouci482 Жыл бұрын
thank you
@halahmilksheikh
@halahmilksheikh 2 жыл бұрын
How is this guaranteed to be balanced? I guess intuitively it makes sense because you're always halving but that doesn't feel like a satisfying answer
@chaitanya_anand
@chaitanya_anand 2 жыл бұрын
Because you are choosing the middle element of array as the current node and the elements to the right and left as right and left subtree. Since you are dividing the array in two equal(or diff. by 1) halves therefore you get balanced tree
@saitharun8114
@saitharun8114 2 жыл бұрын
I tried without a helper function, recursing the given one. But got more processing time. I would appreciate it if you could help me understand why.? ( Note: I am new to DSA) def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: l = 0 r = len(nums)-1 mid = (l+r)//2 if l > r: return None root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[0:mid]) root.right = self.sortedArrayToBST(nums[mid+1:r+1]) return root
@amberfatima2777
@amberfatima2777 Жыл бұрын
i think its because youre sending a part of array as parameters,it increases both space and time complexity ( Note: I am also new to DSA)
@edwardteach2
@edwardteach2 6 ай бұрын
U a God
@MaxFung
@MaxFung 11 ай бұрын
spent 30 minutes on this and this tree STUMPED me
@khoaanh7375
@khoaanh7375 Жыл бұрын
So elegant
@DmitriyKl
@DmitriyKl Жыл бұрын
I think it would be slightly easier to understand this solution without the additional helper function. Basically, you take the middle element, set it as the root node value, and everything to the left of the middle element gets passed down recursively to the same function (and becomes the left subtree), and everything to the right of the middle element gets passed down recursively to the same function as well (and becomes the right subtree): def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: # base case - nums is empty if not nums: return None midIdx = len(nums)//2 root = TreeNode(nums[midIdx]) # middle value becomes root node value root.left = self.sortedArrayToBST(nums[0:midIdx]) # left subtree is everything to the left of the middle root.right = self.sortedArrayToBST(nums[midIdx+1:len(nums)]) # right subtree is everything to the right of middle return root
@nachiket9857
@nachiket9857 Жыл бұрын
I agree, it's more intuitive that way
@aidanfarhi4582
@aidanfarhi4582 9 ай бұрын
This solution will create a copy of each subarray every time you recursively call self.sortedArrayToBST. It's a valid solution but uses more memory than the helper function approach.
@Pushpraj_gour
@Pushpraj_gour Жыл бұрын
The simplest way of explaination this question if is ever existed then that guy has to watch this video to change his opinion
@shalsteven
@shalsteven 2 жыл бұрын
How about the time and space complexity?
@inteligence317
@inteligence317 2 жыл бұрын
In the pharmacy watching this lol I don't have anytime to do shit lol
@sakshisinha8213
@sakshisinha8213 2 жыл бұрын
beauty
@justsomeguy8385
@justsomeguy8385 3 ай бұрын
I wasted so much time trying to come up with an iterative solution...
@akagamishanks7991
@akagamishanks7991 Жыл бұрын
how is this problem easy lol
@antoinenijhuis450
@antoinenijhuis450 10 ай бұрын
I know right, like in my head there are so many edge cases. What happens if the subtrees are of size 1 or 2 etc? I get that his code takes care of all of that, but it is not easy to see that directly I'd say.
@nanobyte8425
@nanobyte8425 3 жыл бұрын
First
@cathyhuang8557
@cathyhuang8557 3 жыл бұрын
Second
@raunaqsingh875
@raunaqsingh875 2 жыл бұрын
If in case someone wants a C++ code: class Solution { public: //Leetcode question # 108 TreeNode* buildTree(vector &nums,int lb,int ub){ if(lb>ub) return 0; int mid=(lb+ub)/2; TreeNode*newNode=new TreeNode(nums[mid]); newNode->left=buildTree(nums,lb,mid-1); newNode->right=buildTree(nums,mid+1,ub); return newNode; } TreeNode* sortedArrayToBST(vector& nums) { int lb=0,ub=nums.size()-1; int mid=(lb+ub)/2; TreeNode*root=new TreeNode(nums[mid]); root->left=buildTree(nums,lb,mid-1); root->right=buildTree(nums,mid+1,ub); return root; } };
Balanced Binary Tree - Leetcode 110 - Python
13:11
NeetCode
Рет қаралды 267 М.
Search in Rotated Sorted Array II - Leetcode 81 - Python
17:36
NeetCodeIO
Рет қаралды 16 М.
Симбу закрыли дома?! 🔒 #симба #симбочка #арти
00:41
Симбочка Пимпочка
Рет қаралды 4,4 МЛН
Twin Telepathy Challenge!
00:23
Stokes Twins
Рет қаралды 94 МЛН
МЕНЯ УКУСИЛ ПАУК #shorts
00:23
Паша Осадчий
Рет қаралды 5 МЛН
Merge Sorted Array - Leetcode 88 - Python
10:18
NeetCode
Рет қаралды 233 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 438 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 500 М.
Implement Trie (Prefix Tree) - Leetcode 208
18:56
NeetCode
Рет қаралды 212 М.
Binary Tree Maximum Path Sum - DFS - Leetcode 124 - Python
15:19
Симбу закрыли дома?! 🔒 #симба #симбочка #арти
00:41
Симбочка Пимпочка
Рет қаралды 4,4 МЛН