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

  Рет қаралды 71,651

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
Coding Solutions: • Coding Interview Solut...
Problem Link: leetcode.com/problems/convert...
0:00 - Read the problem
1:40 - Drawing Explanation
6:32 - Coding Explanation
leetcode 108
This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
#sorted #array #python

Пікірлер: 69
@NeetCode
@NeetCode 3 жыл бұрын
Tree Question Playlist: kzbin.info/www/bejne/hZ-2n2WOerZng7s
@kairokabir9696
@kairokabir9696 2 жыл бұрын
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 10 ай бұрын
what are you doing now? Just curious cause I recently started coding.
@roshangeorge97
@roshangeorge97 8 ай бұрын
Yeah the only explanation i needed for like an hour.
@moulee007
@moulee007 8 ай бұрын
​@@chuckle_pugz96will ask the same question to you after 2 years
@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!
@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
@xjlonelystar
@xjlonelystar 2 жыл бұрын
god, i appreciate you always explain even the most basic things. Absolutely amazing!
@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.
@arturkabitcher
@arturkabitcher Жыл бұрын
That's the best channel for leetcode prep. I know you must be busy with your Google job but keep posting videos - I think you can monetize it even better than any FAANG career
@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!
@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!
@DoJoStan
@DoJoStan 2 жыл бұрын
Amazing explanation.
@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 11 ай бұрын
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 2 ай бұрын
@@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.
@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)?
@jayjagtap7873
@jayjagtap7873 Жыл бұрын
This solution is genious
@shooby117
@shooby117 3 жыл бұрын
Great explanations mate! :D
@NeetCode
@NeetCode 3 жыл бұрын
Thanks!
@ruthylevi9804
@ruthylevi9804 2 жыл бұрын
this is the video that made it click! thank you for explaining the reasoning in necessary detail behind all this :)
@NeetCode
@NeetCode 2 жыл бұрын
Happy it was helpful!
@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 Жыл бұрын
Thank you. Had a same doubt.
@jointcc2
@jointcc2 Жыл бұрын
Thanks. This has cleared my doubt.
@ewanowacka4772
@ewanowacka4772 3 ай бұрын
I was thinking the same and implemented with m = (r+l)//2+1
@asmahamdym
@asmahamdym Жыл бұрын
after watching your explanation I really can't understand from anyone else, Please make more videos
@zooomba62
@zooomba62 11 ай бұрын
thank u fro the great explanation
@sneezygibz6403
@sneezygibz6403 3 жыл бұрын
Thanks man
@geofox9484
@geofox9484 10 ай бұрын
Would this be wrong if I'm getting -10 and 5 as my 1st level after root?
@sushrutasengupta1273
@sushrutasengupta1273 6 ай бұрын
Can it be solved using two while loops seperately??
@KyuriousBot
@KyuriousBot Жыл бұрын
How are we making sure at every step that the subtress are height balanced? Can someone please explain?
@head0fmob
@head0fmob 10 ай бұрын
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
@tabmax22
@tabmax22 Жыл бұрын
Dude if I get into Google I'm genuinely donating 10% of my first pay cheque to you
@roshangeorge97
@roshangeorge97 8 ай бұрын
have you got in?
@foudilbenouci482
@foudilbenouci482 8 ай бұрын
thank you
@khoaanh7375
@khoaanh7375 Жыл бұрын
So elegant
@mohamedsalama2743
@mohamedsalama2743 3 ай бұрын
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 23 күн бұрын
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.
@edwardteach2
@edwardteach2 Ай бұрын
U a God
@CST1992
@CST1992 2 ай бұрын
Memory complexity is still O(n) as you're creating n nodes. How is it O(log n)?
@jobsearch9934
@jobsearch9934 2 жыл бұрын
Wouldn't space complexity still be O(n) since were creating "n" nodes?
@Maattttheww
@Maattttheww Жыл бұрын
Yep, I think that's a mistake.
@saitharun8114
@saitharun8114 Жыл бұрын
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 9 ай бұрын
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)
@shalsteven
@shalsteven 2 жыл бұрын
How about the time and space complexity?
@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
@veliea5160
@veliea5160 Жыл бұрын
in which case `l>r` "l" will be greater "r"
@Pranav-nn1lu
@Pranav-nn1lu Жыл бұрын
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 Жыл бұрын
@@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
@inteligence317
@inteligence317 Жыл бұрын
In the pharmacy watching this lol I don't have anytime to do shit lol
@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
@MaxFung
@MaxFung 7 ай бұрын
spent 30 minutes on this and this tree STUMPED me
@sakshisinha8213
@sakshisinha8213 Жыл бұрын
beauty
@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
@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 5 ай бұрын
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.
@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
@cathyhuang8557
@cathyhuang8557 3 жыл бұрын
Second
@nanobyte8425
@nanobyte8425 3 жыл бұрын
First
@akagamishanks7991
@akagamishanks7991 11 ай бұрын
how is this problem easy lol
@antoinenijhuis450
@antoinenijhuis450 5 ай бұрын
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.
@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; } };
Search in Rotated Sorted Array II - Leetcode 81 - Python
17:36
NeetCodeIO
Рет қаралды 12 М.
아이스크림으로 체감되는 요즘 물가
00:16
진영민yeongmin
Рет қаралды 4,9 МЛН
когда повзрослела // EVA mash
00:40
EVA mash
Рет қаралды 3,9 МЛН
Wait for the last one! 👀
00:28
Josh Horton
Рет қаралды 136 МЛН
That's how money comes into our family
00:14
Mamasoboliha
Рет қаралды 6 МЛН
Diameter of a Binary Tree - Leetcode 543 - Python
15:34
NeetCode
Рет қаралды 217 М.
100+ Linux Things you Need to Know
12:23
Fireship
Рет қаралды 76 М.
Merge Sorted Array - Leetcode 88 - Python
10:18
NeetCode
Рет қаралды 188 М.
Balanced Binary Tree - Leetcode 110 - Python
13:11
NeetCode
Рет қаралды 219 М.
Binary Search Tree in Python
22:59
NeuralNine
Рет қаралды 46 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 612 М.
LARGEST RECTANGLE IN HISTOGRAM - Leetcode 84 - Python
17:20
NeetCode
Рет қаралды 198 М.
Как устроены сенсорные экраны?
16:53
Физика с Юрием Ткачёвым
Рет қаралды 3,5 М.
Мой инст: denkiselef. Как забрать телефон через экран.
0:54
Main filter..
0:15
CikoYt
Рет қаралды 15 МЛН
Опыт использования Мини ПК от TECNO
1:00
Андронет
Рет қаралды 221 М.
iPhone 16 с инновационным аккумулятором
0:45
ÉЖИ АКСЁНОВ
Рет қаралды 3,9 МЛН