L50. Binary Search Tree Iterator | BST | O(H) Space

  Рет қаралды 157,359

take U forward

take U forward

Күн бұрын

Пікірлер: 151
@takeUforward
@takeUforward 3 жыл бұрын
Please do like, that is the only thing which keeps me motivated to make such kind of videos! Your support is all I need :) Follow-up question: Design before and hasBefore!
@siddharthvs1770
@siddharthvs1770 3 жыл бұрын
u make great videos brother! huge respects!
@sayantaniguha8519
@sayantaniguha8519 2 жыл бұрын
Is it possible through one stack ?
@ritikshandilya7075
@ritikshandilya7075 8 ай бұрын
someone asked me : Who is Striver ? My Answer : Striver is a person sent by God to help the helpless and beginners without any self benefit .The person responsible to help the entire community single handedly. Thankyou so much Striver for great explanation.
@rachanasingh2231
@rachanasingh2231 2 жыл бұрын
Words are not enough to thank you for the amount of energy you put into teaching
@prachigoyal2510
@prachigoyal2510 Жыл бұрын
After you gave the hint of stack, I paused the video and was able to solve on my own. Thank you Striver 😇
@pritishpattnaik4674
@pritishpattnaik4674 2 жыл бұрын
Very Beautifully explained Striver bhaiya , wrote the code without seeing the solution In case anybody needs the code , (Done by my own) : class BSTIterator { public: stack st; BSTIterator(TreeNode* root) { //push all the left nodes in the stack while (root != NULL){ st.push(root); root = root->left; } } int next() { TreeNode *currNode = st.top(); st.pop(); if (currNode->right != NULL){ TreeNode *temp = currNode->right; while (temp != NULL){ st.push(temp); temp = temp->left; } } return currNode->val; } bool hasNext() { if (!st.empty()) return true; return false; } };
@satyapraneethkatta1652
@satyapraneethkatta1652 3 жыл бұрын
Really loved your explanation. This series is on another level better than any paid course anywhere Thanks a lot Striver !!!!
@anupamdungdung9417
@anupamdungdung9417 2 жыл бұрын
The way you explain things are beyond expectations! The intuition goes straight in to the memory. Thanks for this awesome playlist!
@BhavanaG-j9e
@BhavanaG-j9e Жыл бұрын
Striver, Thank you for the detailed explanation, It was really helpful Python Solution: class BSTIterator: def __init__(self, root: Optional[TreeNode]): self.stack = [] self.pushAllLeft(root) def next(self) -> int: if self.stack: value = self.stack.pop() self.pushAllLeft(value.right) return value.val def hasNext(self) -> bool: if not self.stack: return False return True def pushAllLeft(self,node): while node: self.stack.append(node) node=node.left
@stith_pragya
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video.............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@bhairavas2528
@bhairavas2528 Жыл бұрын
His Energy and Confidence is definitely inspiring for everyone :)
@yashjain1492
@yashjain1492 3 жыл бұрын
how did you calculate average as o(1) , I didn't understood that part?
@bhaveshkumar6842
@bhaveshkumar6842 2 жыл бұрын
Search "amortized analysis"
@vishious14
@vishious14 Жыл бұрын
Thanks Striver, I was able to code this on my own as soon as you mentioned stack and going right as soon as you pop an element.
@nandpatel924
@nandpatel924 2 жыл бұрын
Explanation was so crisp and to the point. Thanks
@utkarshsaxena7445
@utkarshsaxena7445 2 жыл бұрын
Easy Solution ✔✔ class BSTIterator { public: vector ans; int pos; void inorder(TreeNode *root) { if(root==NULL) return; inorder(root->left); ans.push_back(root->val); inorder(root->right); } BSTIterator(TreeNode* root) { pos=0; inorder(root); } int next() { return ans[pos++]; } bool hasNext() { return ans.size()!=pos; } };
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
if it was allowed to break the tree , we could apply the morris traversal , and could create the linked list of inorder traversal with the same tree , by this we would not use space complexity of O(N) . but ya only if it is allowed to make changes in the tree
@rohithpeddi
@rohithpeddi Жыл бұрын
A solution using Morris Traversal: Time Complexity for next and hasNext: O(1) Space complexity : O(1) class BSTIterator { public: TreeNode* curr = NULL; BSTIterator(TreeNode* root) { TreeNode* c = root, *last = NULL; while(c) { if (!c->left) { if (!last) last = c; else last->right = c, last = c; c = c->right; } else { TreeNode* x = c->left; while(x->right&&x->right!=c) x = x->right; if (x->right) { if (!last) last = c; else last->right = c, last = c; c = c->right; } else x->right = c, c = c->left; } } while(root->left) root=root->left; curr = root; } int next() { int ans = curr->val; curr=curr->right; return ans; } bool hasNext() { return curr; } }; Link for solution: leetcode.com/problems/binary-search-tree-iterator/solutions/3608539/morris-traversal-most-efficient/
@jaiminsolanki5478
@jaiminsolanki5478 3 жыл бұрын
Amazed by the solution, thanks for making it so fun Raj Bhaiya!!
@Zero-ss6pn
@Zero-ss6pn 5 ай бұрын
Energy of Raj in this video is exceptional 😄🤟
@tarunsharma2971
@tarunsharma2971 2 жыл бұрын
Video with your expression is like you are sitting in front of me and here comes the twist that I need to insert this algorithm in my stack...
@paragroy5359
@paragroy5359 Жыл бұрын
Great video. Keep on moving such videos. Super content.
@joichirogaming
@joichirogaming 3 жыл бұрын
Awesome approach👌👌 ... I hope I can think like this someday on my own TT
@leepakshiyadav1643
@leepakshiyadav1643 2 жыл бұрын
most amazing explanation on youtube :)
@lavanyaprakashjampana933
@lavanyaprakashjampana933 2 жыл бұрын
we love your content and we love you.......🖤
@manasranjanmahapatra3729
@manasranjanmahapatra3729 Жыл бұрын
A good explanation for this problem💯.
@sakshisinghal1669
@sakshisinghal1669 2 жыл бұрын
Why the Time complexity is O(1) at 4:28? If we are considering stack space to store the inorder then we should consider time to get inorder as well even if getting next and hasNext() are constant. Can @striver or anyone please explain?
@anonymousvoid6356
@anonymousvoid6356 2 жыл бұрын
Sakshi, The time complexity to create the inorder traversal in the form of array is considered as a prepocessing step (we are doing it just once) We are worried only about the time complexity of the individual calls to the iterator. So TC is O(1) !!!
@anmoldarak
@anmoldarak 2 жыл бұрын
Yes.. you are right.. when someone is calling next, in worst case we have to traverse through the height of the binary tree which is O(logn)
@harpercfc_
@harpercfc_ 2 жыл бұрын
This is the best vid explaining this problem on youtube I dare you. Thank you :)
@RavinderSingh-qb4xi
@RavinderSingh-qb4xi 3 жыл бұрын
couldn't understand how T.C is O(1) at 4:32 as we are storing in vector so it must take O(N) to do so.
@takeUforward
@takeUforward 3 жыл бұрын
Answer storing is not considered
@tps8470
@tps8470 6 ай бұрын
Thank You
@tusharnain6652
@tusharnain6652 2 жыл бұрын
Thank You Striver . . . . . and RELEVEL.
@gaurigupta5129
@gaurigupta5129 Жыл бұрын
Hats off to you!
@karanthakur11
@karanthakur11 11 ай бұрын
Dry run : 5:48
@evolver92
@evolver92 Жыл бұрын
time complixity that striver mentioned is for average case which is O(1) in worst case the time complixity is O(N)
@apmotivationakashparmar722
@apmotivationakashparmar722 2 ай бұрын
Great Striver !
@vibhu613
@vibhu613 2 жыл бұрын
Kya energy hai bhaiya🥰
@sanjaykeshwar2100
@sanjaykeshwar2100 2 жыл бұрын
Can be done in S.C: O(1) using Morris Traversal.
@pjagannadham2540
@pjagannadham2540 3 жыл бұрын
Bhayya u r super first I think it is complicated but ur teaching is like very simple and I really really understood it
@atharvakulkarni2024
@atharvakulkarni2024 3 жыл бұрын
Beautifully explained bro!!Thanks a lot!!
@AdityaKumar-be7hx
@AdityaKumar-be7hx Жыл бұрын
If anyone is wondering how to solve the merging of BST - here's my solution using the iterator ( I added peek() to make it easier to compare. class BSTIterator{ private: stackst; public: BSTIterator(Node* root){ push_all(root); } //return if more elements are left in tree traversal or not. bool hasNext(){ return !st.empty(); } //return the next item in inorder traversal. int next(){ Node* temp=st.top(); st.pop(); if(temp->right){ push_all(temp->right); } return temp->data; } int peek(){ return st.top()->data; } private: void push_all(Node* root){ while(root){ st.push(root); root=root->left; } } }; class Solution { public: //Function to return a list of integers denoting the node //values of both the BST in a sorted order. vector merge(Node *root1, Node *root2) { vector ans; BSTIterator a(root1); BSTIterator b(root2); while(a.hasNext() and b.hasNext()){ if(a.peek()
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
great man , nice approach
@DeadPoolx1712
@DeadPoolx1712 Ай бұрын
UNDERSTOOD;
@Learnprogramming-q7f
@Learnprogramming-q7f 9 ай бұрын
Thank you Bhaiya
@editorera239
@editorera239 3 жыл бұрын
Bro tum hi ho hmare liye jo ho thanks Love u bro
@vivek5144
@vivek5144 3 жыл бұрын
Guru ji can u please tell me how i improve my thought process about the questions. Jaadtar question me help leni padti h aapki videos ki, solution to soch leta hu ki aise krunga but code likhne me problem hoti h. Agr time mile to please reply kar dijiyega 🙏
@ritikshrivastava9442
@ritikshrivastava9442 2 жыл бұрын
if you can think the solution and not able to code then you don't have command over the language whatever the language you have chosen try to clear basics of it
@HemanthKumar-bl1yt
@HemanthKumar-bl1yt 3 ай бұрын
@@ritikshrivastava9442 im having trouble with thought process
@bhagyashreekhairnar683
@bhagyashreekhairnar683 9 ай бұрын
Thank you !!
@deekshithtirumala6474
@deekshithtirumala6474 Жыл бұрын
🥵 you are the reference for our sir. OP level videos broooo..🥵🥵🥵🥵🥵
@AmanKumar-xw5bs
@AmanKumar-xw5bs 8 ай бұрын
But in case of skewed bst, the space complexity will still be O(n)
@yuzhou9893
@yuzhou9893 2 жыл бұрын
bruh, your energy is something else
@AnshKumar-dp1st
@AnshKumar-dp1st 2 жыл бұрын
Can't we apply this approach in "Binary tree"? or why is it limited to "Binary Search Tree" only??
@rohanprasad97
@rohanprasad97 3 жыл бұрын
Can anyone help me understand how the Space Complexity is O(H), since we are putting all the elements in the stack (check the stack at 10:55), if we are pushing all the elements then the Space Complexity should be O(N) right? Any help will be really appreciated!
@amanbhadani8840
@amanbhadani8840 3 жыл бұрын
Here space complexity is the height of BST because if you see carefully at any moment of time stack only contains the number of nodes at max the height of tree.Because what we are doing ,simply take out the top element of stack and pop it out and push all its left left left .....element so it can go max to max the height of tree. You will not find any moment where stack containing all the nodes because we are also popping out the top element. At 10:55 stack is actually empty,space complextiy is the size of stack and is analysed by the max no of nodes that is present at any particular instant of time.Hope all your doubts are cleared now.
@joseph2073
@joseph2073 2 жыл бұрын
@@amanbhadani8840 bhaiya could u plz explain why TC is o(1) and not o(n) ?
@bhaveshkumar6842
@bhaveshkumar6842 2 жыл бұрын
@@joseph2073 Search "amortized analysis"
@joseph2073
@joseph2073 2 жыл бұрын
@@bhaveshkumar6842 ok thanks😀
@SibiRanganathL
@SibiRanganathL 2 ай бұрын
Understood
@niharikamurulidhara7017
@niharikamurulidhara7017 2 жыл бұрын
Plz explain how time complexity is O(N/N) i.e., O(1)
@theLonelyBandit6984
@theLonelyBandit6984 5 ай бұрын
Another approach may be to flatten the tree into inorder in O(h) space
@Tatiana-zu1gf
@Tatiana-zu1gf 3 жыл бұрын
Thank you, very good explanation
@anmoldarak
@anmoldarak 2 жыл бұрын
I think TC is not O(1), it is O(logn) because when you are calling next, in worst case scenario you need to traverse entirely through the height of the tree (approximately). Hence O(logn)
@yashmundada2483
@yashmundada2483 5 ай бұрын
Aren't we storing the nodes in the stack... Doesn't that make the time complexity worse than the inorder traversal where we are only storing the values. Since a node could have in the worst case (root) info about N other nodes?
@per.seus._
@per.seus._ 11 ай бұрын
UNDERSTOOD
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@nishantgautam4343
@nishantgautam4343 2 жыл бұрын
Hey everyone, I coded this using both approaches, one with T.C. O(n) & S.C. O(n) using arrayList, and the other with Stack which is T.C. O(n) & S.C. O(h). But at leetcode the first one took both less time and space, which is unusual. Did it happen with you all too?
@abhirupbasu3386
@abhirupbasu3386 Жыл бұрын
same thing happening with me too.
@HimanshuYadav-pp2ue
@HimanshuYadav-pp2ue Жыл бұрын
bro don't see space and time which leetcode show as it depend on leetcode server it will vary every time you submit the same code
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
yeh may be he used morris traversal to convert same tree to a linked list , just like what we did in flatten tree , and after getting a linked list it would be easier then
@shivamverma-mt6kp
@shivamverma-mt6kp 2 жыл бұрын
Great Explanation, Thanks
@noobcreations9556
@noobcreations9556 3 жыл бұрын
hello striver bhai, aap kounsa writing/digital pad use karte ho?
@dipeshsaili4468
@dipeshsaili4468 3 жыл бұрын
IPAD
@harshitjaiswal9439
@harshitjaiswal9439 10 ай бұрын
understood.
@iamloking
@iamloking 2 жыл бұрын
Really liked the explanation
@chiragbansod8252
@chiragbansod8252 10 ай бұрын
understood
@harshapriyaannapureddy5103
@harshapriyaannapureddy5103 3 жыл бұрын
Did not understand how time complexity is O(1)
@bhaveshkumar6842
@bhaveshkumar6842 2 жыл бұрын
Search "amortized analysis"
@GirishJain
@GirishJain 3 жыл бұрын
Basically the same idea of Inorder Traversal
@Panichusko
@Panichusko Жыл бұрын
class BSTIterator { public: void inorder(TreeNode* root , vector& v1) { if(!root)return; inorder(root->left,v1); v1.push_back(root->val); inorder(root->right,v1); } vector v1; int i=0; BSTIterator(TreeNode* root) { inorder(root,v1); } int next() { i++; return v1[i-1]; } bool hasNext() { if(i+1
@abhaytiwari6411
@abhaytiwari6411 3 жыл бұрын
Explanation 👌👏👍👍
@suryakiran2970
@suryakiran2970 2 жыл бұрын
Super explanation
@karthik-varma-1579
@karthik-varma-1579 2 ай бұрын
class BSTIterator { Stack st; public BSTIterator(TreeNode root) { st = new Stack(); addLeft(root); } public void addLeft(TreeNode root){ TreeNode cur = root; while(cur!=null){ st.push(cur); cur = cur.left; } } public int next() { TreeNode peek = st.pop(); if(peek.right!=null) addLeft(peek.right); return peek.val; } public boolean hasNext() { return !st.isEmpty(); } }
@i_m_mandeep_singh8365
@i_m_mandeep_singh8365 Жыл бұрын
YOU ARE AWESOME MAN!!!!!!!!
@sanskrutishahu517
@sanskrutishahu517 Жыл бұрын
does flattening bst will work??
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
yaa it will work ig. but we have to flatten it according to the inorder
@tanmayjain5821
@tanmayjain5821 6 ай бұрын
How is space complexity O(H)? in the worst case we can have n element all on the left which will bring up space complexity to O(N).
@txbankush4601
@txbankush4601 6 ай бұрын
then height will be N too so O(H)=O(N) in that case
@ritishkalia2487
@ritishkalia2487 3 жыл бұрын
can someone explain why we used private in declaring stack and performing pushall function
@bhaveshkumar6842
@bhaveshkumar6842 2 жыл бұрын
It's a good practice (an essential quality actually) in OOP to hide member variables and methods. This video beautifully explains OOP concepts: kzbin.info/www/bejne/mITVnmyIjdx1l6s
@krishnaradhey2814
@krishnaradhey2814 Жыл бұрын
LEETCODE 173 Problem;
@ritikshrivastava9442
@ritikshrivastava9442 2 жыл бұрын
5 / 4 / 3 / 2 / 1 in this case o(H) is O(n) so still the worst case space complexity is still O(N).
@only_for_fun1234r
@only_for_fun1234r Жыл бұрын
For skew o(n) for balance logn
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
ok just apply morris traversal , you will get your answer in O(1) space
@kmindu9616
@kmindu9616 3 жыл бұрын
Thank you so much for this!!
@leetcoder1159
@leetcoder1159 3 жыл бұрын
Ok
@bhaveshkumar6842
@bhaveshkumar6842 2 жыл бұрын
Striver, you're the best.
@GURU-lz1iw
@GURU-lz1iw Жыл бұрын
Can you solve it using linked list. I mean we can do inorder traversal ans store each node in a linked list and then iterate over it... Can you please share the code for the same.
@AkashBisht-cq3ys
@AkashBisht-cq3ys 5 ай бұрын
1st august 2024 5.05 pm
@abcsumits
@abcsumits 2 жыл бұрын
why not use morris trversal and flantend binary tree to linked list
@abcsumits
@abcsumits 2 жыл бұрын
it will be o(1) approach
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
@@abcsumits space wise it will O(1)
@Anonymous-uj3jx
@Anonymous-uj3jx 2 жыл бұрын
Understood thanks :)
@venutalla5932
@venutalla5932 Жыл бұрын
❤❤❤
@prajitbanerjee8226
@prajitbanerjee8226 Жыл бұрын
your code is beautiful.
@jatinarya3514
@jatinarya3514 10 ай бұрын
50 done
@bibhabendumukherjee9247
@bibhabendumukherjee9247 3 жыл бұрын
please via dp ka series start karo . please
@vaalarivan_p
@vaalarivan_p Жыл бұрын
4:25 - 7:49
@AKASHKUMAR-li7li
@AKASHKUMAR-li7li 6 ай бұрын
class BSTIterator { stack st; public: BSTIterator(TreeNode* root) { st.push({root, 0}); } int next() { while(!st.empty()){ pair tp = st.top(); if(tp.second == 0){ st.top().second++; if(tp.first->left) st.push({tp.first->left, 0}); } else if(tp.second == 1){ int val = tp.first->val; st.pop(); if(tp.first->right) st.push({tp.first->right, 0}); return val; } else { st.pop(); } } return -1; } bool hasNext() { if(!st.empty()) return true; return false; } };
@roopeshn3301
@roopeshn3301 2 жыл бұрын
Understood
@dineshchintu9779
@dineshchintu9779 3 жыл бұрын
thanks, striver !!
@goooo9561
@goooo9561 2 жыл бұрын
Using morris traversal : TreeNode* cur; BSTIterator(TreeNode* root) { cur=root; } int next() { if(cur->left==NULL) { int value=cur->val; cur=cur->right; return value; } else{ while(cur->left!=NULL) { TreeNode *pre=cur->left; while(pre->right&&pre->right!=cur) { pre=pre->right; } if(pre->right==NULL) { pre->right=cur; cur=cur->left; } else{ pre->right=NULL; int value=cur->val; cur=cur->right; return value; } } int value=cur->val; cur=cur->right; return value; } return -1; } bool hasNext() { return cur!=NULL; }
@casinarro
@casinarro 2 жыл бұрын
The personification 😂 Anyways thanks a lot!!
@tushar5359
@tushar5359 Жыл бұрын
Nice ❤
@rishabhgupta9846
@rishabhgupta9846 2 жыл бұрын
understood
@khushinaudiyal2786
@khushinaudiyal2786 2 жыл бұрын
Can anyone please explain this statement-- ? for(; root!=NULL; st.push(root), root=root->left);
@aakriti1
@aakriti1 2 жыл бұрын
You can use below snippet too: while(root!=NULL) { stk.push(root); root=root->left; } Both snippets basically means that keep pushing all the left nodes of the root in the stack till the root is not equal to the NULL.
@only_for_fun1234r
@only_for_fun1234r Жыл бұрын
@@aakriti1 i was writing the same thing
@girikgarg8
@girikgarg8 Жыл бұрын
Done!
@mrrishiraj88
@mrrishiraj88 3 жыл бұрын
Thanks a lot👍
@vineethkumar8273
@vineethkumar8273 Жыл бұрын
can anyone share the code for the follow up question for before() and hasBefore() methods ?
@ajayypalsingh
@ajayypalsingh 2 жыл бұрын
💚
@AshokKumar-ii4qr
@AshokKumar-ii4qr 2 жыл бұрын
I can code but can't calculate time complexity 🙂
@danishmukhtar9250
@danishmukhtar9250 3 ай бұрын
We can optimise space to O(1) if we use morris traversal ``` class BSTIterator { public: TreeNode* cur = NULL; pair NextMoris(TreeNode* root){ while(root!=NULL){ if(root->left==NULL){ int ans = root->val; root = root->right; return {ans,root}; }else{ TreeNode* node = root->left; while(node->right && node->right!=root){ node = node->right; } if(node->right == NULL){ node->right = root; root = root->left; }else{ root = node->right; int ans = root->val; root = root->right; node->right = NULL; return {ans,root}; } } } return {0,NULL}; } BSTIterator(TreeNode* root) { cur = root; } int next() { pair p = NextMoris(cur); cur = p.second; return p.first; } bool hasNext() { return cur!=NULL; } }; ```
@iamnoob7593
@iamnoob7593 10 ай бұрын
US
L51. Two Sum In BST | Check if there exists a pair with Sum K
15:06
take U forward
Рет қаралды 160 М.
L52. Recover BST | Correct BST with two nodes swapped
15:56
take U forward
Рет қаралды 140 М.
SLIDE #shortssprintbrasil
0:31
Natan por Aí
Рет қаралды 49 МЛН
"Идеальное" преступление
0:39
Кик Брейнс
Рет қаралды 1,4 МЛН
БОЙКАЛАР| bayGUYS | 27 шығарылым
28:49
bayGUYS
Рет қаралды 1,1 МЛН
Binary Search Tree Iterator - Leetcode 173 - Python
12:47
NeetCode
Рет қаралды 45 М.
7 Outside The Box Puzzles
12:16
MindYourDecisions
Рет қаралды 325 М.
Transformers (how LLMs work) explained visually | DL5
27:14
3Blue1Brown
Рет қаралды 4,3 МЛН
Big-O Notation - For Coding Interviews
20:38
NeetCode
Рет қаралды 548 М.
L44. Delete a Node in Binary Search Tree | BST | C++ | Java
15:48
take U forward
Рет қаралды 224 М.
7 Лет Опыта в IT | Что я Понял?
19:56
Vlad Mishustin
Рет қаралды 255 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 519 М.
SLIDE #shortssprintbrasil
0:31
Natan por Aí
Рет қаралды 49 МЛН