This solution is optimal and works only when the constraint that both the nodes are actually in the tree. While not a better approach than the one shown in this video, I went with implementing a visitor pattern to cover the case where any node is not in the tree. This brings the TC to O(H) and SC to O(H) as well. The idea is to keep an expanding array. During the visit to search first item, we add the value to the array at the end. If not found, return null then and there. Now, initialize a variable idx to -1. Then search for second item, and while visiting each node, check if the array[idx + 1] element is the same as the current node. If yes, increment idx. Finally if the node is not found, or if idx stays at -1, return null. Else you can return array[idx] which is the LCA.
@crazycr73312 жыл бұрын
He had cover this edge test case on Previous LCA video
@galleryofjatin192 жыл бұрын
i have been watching this playlist from last 2 week and practicing problems, but now when you tell the split approach i was just stunned and rn im at @5:12 , I paused the video and writing this comment ! Seriously India need more brilliant mentors and teachers like you!
@kushalroy9747 Жыл бұрын
Man u are right. I was stunned for a sec!!
@VikasGupta-ok9lh Жыл бұрын
Same man
@nikhilmadaan296 ай бұрын
exactly same experience
@shubhamkumarsingh88185 ай бұрын
man, u r genius. what a brilliant way of teaching.
@karthik-varma-1579Ай бұрын
Thanks Stirver for Tree ka playlist i was able to solve this problem by myself. Thanks a lot.
@prajapati-suraj3 ай бұрын
I struggled for 2 hours because I was considering bst as bt.... thank you so much for this...
@aaluSandwich3 жыл бұрын
Hope the haters watch the video once instead of just barging and disliking. Thank you so much bhaiya for such amazing content.
@VinayKumar-ze2ww2 жыл бұрын
This guy has haters? He is an inspiration bro🙂
@SibiRanganathL22 күн бұрын
Great approach
@priyankasetiya13585 ай бұрын
·class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==null){ return null; } int current = root.val; if(currentq.val){ return lowestCommonAncestor(root.left,p,q); } else{ return root; } } }
@culeforever54089 ай бұрын
Great Series 😀
@diegolikescode9 ай бұрын
Man, really good stuff!! Thank you for this!
@amanjotsingh58762 жыл бұрын
Good explanation .... just one thing bro control your hands movement 😂😂 ... jokes apart..... keep up the good work
@vivekjaiswar68253 жыл бұрын
Hey striver i followed your entire tree series but still i can't remember some of the concepts in previous videos. What should i do?
@takeUforward3 жыл бұрын
Notes..
@real-investment-banker2 жыл бұрын
And Revision...
@codding32world502 жыл бұрын
Same here buddy no one can except if you are prodigy... SO REVISION IS THE KEY
@avanishmaurya203410 ай бұрын
Nice
@subirkumar6786 Жыл бұрын
What if node p is present and node q is not present in the BST
@GauravGangwar-r2v5 ай бұрын
bro is genius .
@priyankaranawat83733 ай бұрын
Thank you sooooo much
@ishwaripednekar51642 жыл бұрын
Keep it up, we need teachers like you!!
@aaranyaksantra99334 ай бұрын
nice solution
@himanshidafouty3474 ай бұрын
Understood
@Preethamdivakar4 ай бұрын
super explaination bro🙏
@shwetanksingh52082 жыл бұрын
//Iterative code with less number of comparisons and no stack space class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { int minVal = min(p->val,q->val),maxVal = max(p->val,q->val); while(root) { if(root->valright;//both values are on right of current node else if(root->val>maxVal) root = root->left;//both values are on left of current node else break;//this node is LCA of p and q } return root; } };
@nishant1720 Жыл бұрын
what in the case of skewed tree like 1->right = 2, 2->right = 3;
@apmotivationakashparmar722Ай бұрын
Thank you So much !
@zeyadalbadawy2245 Жыл бұрын
Amazing sir
@arpanseal5722 Жыл бұрын
Hello sir, thanks for providing such amazing video tutorials. I can't understand why are you writing the base case here? Is there any need to do that?
@takeUforward Жыл бұрын
You can ignore if it works without them, I usually write it for cleaner code
@arpanseal5722 Жыл бұрын
@@takeUforward Thank you sir. Got it. ❤️
@GhostVaibhav9 ай бұрын
Understood🔥
@Shubham-yc6nz3 ай бұрын
Thanks
@babai21962 жыл бұрын
can this approach be applied to lca of binary tree
@khitijkarmakar Жыл бұрын
nope
@iamnottech89184 ай бұрын
Wow!
@Learnprogramming-q7f8 ай бұрын
thank you Bhaiya
@hakunamatata-nl4js5 ай бұрын
thank you
@ishangujarathi10 Жыл бұрын
loved the intuition, amazing explanation as alwaysss!!!! tysm!!!
@arpanbanejee51433 жыл бұрын
Thanks for this awesome series! you are the best!
@harshitjaiswal94399 ай бұрын
understood
@ashishchandra40782 жыл бұрын
crystal clear explanation. Thank you Striver.
@swayam503 жыл бұрын
Amazing video as always, you're tree series is helping a lot 🙂🙂
@shikharai-tl4vb5 ай бұрын
good job :)
@saranguru61003 жыл бұрын
Hi Striver, if the same question is extended and if they given an array of nodes and if asked to find lca? How to do?
@ashpreetsidana66742 жыл бұрын
build the BST from array(you need to sort an array) and then perform LCA
@saranguru61002 жыл бұрын
@@ashpreetsidana6674 This consume too much time I guess!! Any efficeient way ?
@editorera2393 жыл бұрын
bhai kaafi pro level intuition h Thanks!
@ashuraj19812 жыл бұрын
Do u read every comments striver, just asking.By the way thanks a lot for #FreekaTreeSeries❤
@akashnandi1267 Жыл бұрын
1 is missing bro pls correct it
@RAJKUMAR-q4c2x10 ай бұрын
what if p and q are not present in BST ??
@codebits21202 жыл бұрын
Very clear explanation
@rishabhprasad83333 жыл бұрын
In the code, if we do not write 'return' before recursive calling the lowestCommonAncestor function, then also it is giving correct output. Then what's the purpose of writing it?
@MeenakshiSharma-bd3bu2 жыл бұрын
No it's not working if you do not write return before recursive call bcz if you will not write return than it will return actual root of bst at the end so its mandatory to write return before recursion as than it will return the root of LCA
@lakshayrastogi23472 жыл бұрын
phele se sb krke baitha h bhai? : (
@chirlasowmyareddy Жыл бұрын
geeks for geeks accepted solution using while loop ...hope this helps... Node* LCA(Node *root, int n1, int n2) { //Your code here while(root){ if(root->data==n1 || root->data==n2) { return root; } else if(root->data>n1 && root->datadatadata>n2){ return root; } else if(root->data>n1){ root=root->left; } else{ root=root->right; } } }
@thebibeksaha2 жыл бұрын
It's my solution but it takes O(2h) extra space and O(n) time class Solution { private void fillSet(TreeNode root, TreeNode targetNode, Set set) { TreeNode curr = root; while (curr != targetNode) { set.add(curr); if (targetNode.val < curr.val) curr = curr.left; else curr = curr.right; } set.add(curr); } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; Set setOne = new LinkedHashSet(); Set setTwo = new LinkedHashSet(); fillSet(root, p, setOne); fillSet(root, q, setTwo); setOne.retainAll(setTwo); TreeNode lca = null; for (TreeNode node : setOne) lca = node; return lca; } }
@parthsalat2 жыл бұрын
Here are my detailed notes on this question: garmadon.notion.site/Lowest-Common-Ancestor-of-a-Binary-Search-Tree-f568d9e1505f4234bdbd045516e0d4e5
@tech_wizard93153 жыл бұрын
I am a DSA beginner,is your trees series enough to crack tech giant's like Microsoft linkedin level companies?
@Kpriyasing3 жыл бұрын
Thanks for such a nice explanation!
@krishnarajs9292 жыл бұрын
if the given p and q nodes is not there .what we need to do?
@optimus_prime01 Жыл бұрын
return -1
@kwakubiney5175 Жыл бұрын
Why does it work without the base case check? It works well without `if root == null{return root;}`
@priyanshshah6126 Жыл бұрын
because both the nodes exists in the tree is the criteria in leetcode
@prachigupta2430 Жыл бұрын
Thanks for this much amazing content and explanation. Again very grateful 😊
@ishaanchandak1258 Жыл бұрын
link of the question ?
@deepakojha32163 жыл бұрын
bhaiya Dp kab se ayegi .... tree is about to finish i think ...!! few videos left ......Loved your tree series eagerly waiting for the DP series..... please upload it soon...!! you promised us to upload DP on DIWALI...!!
@takeUforward3 жыл бұрын
I promised if you give me 10k likes, you did not 🥲 Anyways will be up from Dec 1
@PrinceKumar-el7ob3 жыл бұрын
@@takeUforward bhaiya thodi jldi november m hi upload krdo placement season hai december m 😿. like to bhaiya aa jayenge content hi aise hai 💓.
Line 13 should be : if(root == NULL) return root ;
@igaming_2 жыл бұрын
U can write return null or return root (both are correct)
@prafuljohn152 жыл бұрын
Striver bhai c++ pr chal nahi raha hai aapka code
@iamnoob75939 ай бұрын
US
@ishwaripednekar51642 жыл бұрын
This is just outstanding
@shivalikagupta34332 жыл бұрын
Thank you so mcuh for all your hard work !!!
@DevanshuAugusty Жыл бұрын
tc = logn right?
@only_for_fun1234r Жыл бұрын
No, think of shew bst it will be o(n)
@DevanshuAugusty Жыл бұрын
@@only_for_fun1234r yes you are right . thanx
@sammedpatil39072 жыл бұрын
nice explanation....
@SiddheshKukade Жыл бұрын
thanks
@player-te8tf2 жыл бұрын
striver runs java code in c++ mode (7:52) on leetcode, halke me mt lena god hai bro apna
@deeyasings2 жыл бұрын
understood
@UECAshutoshKumar Жыл бұрын
Thank you sir
@anonymous090 Жыл бұрын
Thank you Bhaiya
@sayakbasak587 Жыл бұрын
thanks bhaiya
@debugagrawal2 жыл бұрын
DSA God 😍🙌🚩🚀
@alesblaze47452 жыл бұрын
thanks mate!
@venutalla5932 Жыл бұрын
Tq sir
@roopeshn33012 жыл бұрын
Understood
@atifali34855 күн бұрын
Is this correct? TC-> O(H) SC-> O(1) // Iterative soltion class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(true){ if(root==null) return null; if((root.val>p.val && root.val p.val && root.val>p.val) root=root.left; else root=root.right; } } }
@bhaveshrathod98982 жыл бұрын
Thanks for the video:)
@abhishek__anand__ Жыл бұрын
Super
@ajayypalsingh2 жыл бұрын
💚
@BharatVaad2 жыл бұрын
great
@rishabhgupta9846 Жыл бұрын
able to solve by myself
@NikhilGupta-zo5jh2 жыл бұрын
UnderStood
@piyushacharya76962 жыл бұрын
// Iterative Approach JAVA: Beats 100%🔥 package DataSructures.BST; public class LCAInBST { // time complexity: O(height) -> not recommended to use the BT way of solving, since it gives tc of O(n) public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode lca = findNode(root, p, q); return lca; } private TreeNode findNode(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; while (root != null) { // this ensures that we reach the lca. Using the property of BST if (root.val >= Math.min(p.val, q.val) && root.val = Math.max(p.val, q.val)) { root = root.left; } else { root = root.right; } } return root; } }
@tejalsaraswat Жыл бұрын
u r the besttt
@aditya14-023 жыл бұрын
Awesome code,video keep it uo
@605_samikrdas4 Жыл бұрын
soooo goood trulyyy
@suvanshmahajan59022 жыл бұрын
"us"
@dreamyme5432 жыл бұрын
Understood:)
@theonlyisteve72612 жыл бұрын
shit got real, nice1
@ashutoshtripathi82573 жыл бұрын
🔥🔥❤️
@hitheshpk60303 ай бұрын
Understood
@abhinanda70496 ай бұрын
understood
@tech_wizard93153 жыл бұрын
I am a DSA beginner,is your trees series enough to crack tech giant's like Microsoft linkedin level companies?