Це відео не доступне.
Перепрошуємо.

L51. Two Sum In BST | Check if there exists a pair with Sum K

Поділитися
Вставка
  • Опубліковано 19 сер 2024
  • Entire DSA Course: takeuforward.o...
    Check our Website:
    Linkedin/Instagram/Telegram: linktr.ee/take...
    #treeSeries #striver #placements

КОМЕНТАРІ • 168

  • @ayushidalal5488
    @ayushidalal5488 Рік тому +41

    Words aren't enough to explain how grateful we are to learn from you and that too for free. Thankyou so much Striver! :)

  • @_-6912
    @_-6912 2 роки тому +77

    Thank you for your effort Striver, you are making a difference.

    • @parthsalat
      @parthsalat Рік тому

      Is that morse code?

    • @lilgainz
      @lilgainz 6 місяців тому +1

      He made the difference bro now its our turn

    • @_-6912
      @_-6912 6 місяців тому

      @@parthsalat what do you mean? Please clarify

  • @abhiroopsingh9320
    @abhiroopsingh9320 10 місяців тому +5

    Searched across whole UA-cam but no one has taught this method. ThankYou Striver! :)

  • @prernachaurasia9743
    @prernachaurasia9743 2 роки тому +9

    bhiya, aap kaa coding style bohot neat, clear hai. Bohot awesome code karte ho aap, pata nhi mai kab apne se aise code kar paungi...

  • @devanshmesson2777
    @devanshmesson2777 2 роки тому +20

    I would say, this is an amazing approach!
    Thank you so much Striver, Your Tree Series has helped a lot!

  • @sreerammuthyam6835
    @sreerammuthyam6835 2 роки тому +6

    The way you explain the intution was excellent sir. The code quality is also awesome sir. You are helping a lot of students sir. Thanks from the bottom of my heart.

  • @hardikagarwal3938
    @hardikagarwal3938 2 роки тому +6

    Brilliant analogy drawn from the BST iterator probelm

  • @AyushGupta-kp9xf
    @AyushGupta-kp9xf 2 роки тому +17

    This was so intuitive , learnt a lot. huge thanks man !

  • @souravsinha4173
    @souravsinha4173 2 роки тому +3

    Wow!!! Never seen anyone explain something with this ease!!!

  • @priyanshukoshta2307
    @priyanshukoshta2307 Рік тому +5

    Amazing way to use 2 pointers approach in BST. Thanks alot👍

  • @shikharathaur6664
    @shikharathaur6664 2 роки тому +6

    Efforts you put while explaining is just hats off !
    Thankyou Striver !

  • @harshmittal3128
    @harshmittal3128 Рік тому +6

    This explanation and quality of code was exceptional, thanks a lot striver

  • @rohitsai806
    @rohitsai806 Рік тому +3

    Just blew my mind...! Best explanation...Thank you for the series

  • @LBK3
    @LBK3 Рік тому +2

    this vedio helped me to reduce classes for my code for building an atm machine using classes code in an interview thank you so much striver .....

  • @aashishmittal79
    @aashishmittal79 6 місяців тому +1

    If there can be equal values in the BST, we can return the TreeNode pointer instead of returning its value. Then, we just check if left==high pointer in while loop.

  • @debasmitamondal3519
    @debasmitamondal3519 29 днів тому

    Amazing ! just grateful for this kind of content

  • @debugagrawal
    @debugagrawal 2 роки тому +2

    we can use SET while traversing in inorder, so timecomplexity==N, space complexity==N i.e N < 2*H

    • @bikramgoswami4750
      @bikramgoswami4750 2 роки тому +2

      same thought but in most cases Space complexity O(N > 2H) will be there

  • @harshvardhan1214
    @harshvardhan1214 21 день тому

    Another way of doing it by using and unordered_Set
    class Solution {
    public:
    bool findTarget(TreeNode* root, int k) {
    unordered_set set;
    return dfs(root,k,set);
    }
    bool dfs(TreeNode* root , int k , unordered_set&set){
    if(!root) return false;
    if(set.count(k-root->val))return true;
    set.insert(root->val);
    return dfs(root->left,k,set) || dfs(root->right,k,set);
    }
    };

  • @1tav0
    @1tav0 2 роки тому +4

    this is amazing thank you striver you're truly a role model

  • @ganjinaveen7338
    @ganjinaveen7338 8 місяців тому +1

    this is even similar like two sum problems
    visit=set()
    q=[root]
    for i in q:
    if (k-i.val) in visit:return True
    visit.add(i.val)
    if i.left:
    q.append((i.left))
    if i.right:
    q.append(i.right)
    return False

  • @kunalsaha9239
    @kunalsaha9239 2 роки тому +13

    Dada please tell when we are going to get the free ka Dp Series..... Any estimate date??
    btw this tree series is truly helpful for me.

  • @pratapsingh9638
    @pratapsingh9638 Рік тому +3

    thankyou @striver for providing this quality content for free.You are doing the great job and i hope we will be finding such premium content from your side.

  • @akhilesh59
    @akhilesh59 2 роки тому +4

    Understood.
    Thank you Bhaiya for this awesome Series :)

  • @dayashankarlakhotia4943
    @dayashankarlakhotia4943 Рік тому +1

    Class solution { Hash seths=new hash set();
    Public boolean find Target (Treenode root,int k,){
    If(root ==null)return false;
    If(hs.contain(root. Val)return true;
    Hs.add(k-root.val);
    Find Target (root. right,k)||find Target (root. left,k)

  • @shivangisrivastava1158
    @shivangisrivastava1158 2 роки тому +3

    Yrr mind blown man, highest respect to your series man!

  • @tushar5359
    @tushar5359 Рік тому +2

    This code demonstrates why we should use class 🗿🧐

  • @sayandey2492
    @sayandey2492 6 місяців тому

    Fantastic problem and Fantastic explanation !!

  • @stith_pragya
    @stith_pragya Рік тому +1

    Thank You So Much Striver Brother...🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @dank7044
    @dank7044 2 місяці тому

    this was a very creative approach.

  • @arupdas2210
    @arupdas2210 Рік тому +1

    we cannot do l.hasNext()!=NULL && r.hasNext()!=NULL instead of i

  • @AKASHKUMAR-li7li
    @AKASHKUMAR-li7li Місяць тому

    Just follow the same two pointer approach as used in the array, but in tree😀
    class Solution {
    public:
    struct Pair{
    TreeNode* node;
    int state;
    Pair(TreeNode *node, int state){
    this->node = node;
    this->state = state;
    }
    };
    TreeNode* getNextInorderFromNormalStack(stack &ls){
    while(!ls.empty()){
    Pair tp = ls.top();
    if(tp.state == 0){
    ls.top().state++;
    if(tp.node->left) {
    Pair p = Pair(tp.node->left, 0);
    ls.push(p);
    }
    } else if(tp.state == 1){
    ls.top().state++;
    TreeNode* n = tp.node;
    if(tp.node->right) {
    Pair p = Pair(tp.node->right, 0);
    ls.push(p);
    }
    return n;
    } else if(tp.state == 2){
    ls.pop();
    }
    }
    return nullptr;
    }
    TreeNode* getNextInorderFromReverseStack(stack &rs){
    while(!rs.empty()){
    Pair tp = rs.top();
    if(tp.state == 0){
    rs.top().state++;
    if(tp.node->right) {
    Pair p = Pair(tp.node->right, 0);
    rs.push(p);
    }
    } else if(tp.state == 1){
    rs.top().state++;
    TreeNode* n = tp.node;
    if(tp.node->left) {
    Pair p = Pair(tp.node->left, 0);
    rs.push(p);
    }
    return n;
    } else if(tp.state == 2){
    rs.pop();
    }
    }
    return nullptr;
    }
    bool findTarget(TreeNode* root, int k) {
    stack ls;
    stack rs;
    ls.push({root, 0});
    rs.push({root, 0});
    TreeNode* left = getNextInorderFromNormalStack(ls);
    TreeNode* right = getNextInorderFromReverseStack(rs);
    while(left->val < right->val){
    if(left->val + right->val < k){
    left = getNextInorderFromNormalStack(ls);
    } else if(left->val + right->val > k){
    right = getNextInorderFromReverseStack(rs);
    } else {
    return true;
    }
    }
    return false;
    }
    };

  • @murarichaudhary5602
    @murarichaudhary5602 7 днів тому +1

    love it man ;)

  • @subiyasiddiqui2841
    @subiyasiddiqui2841 2 роки тому +1

    thank you striver for your entire efforts...thanks alot

  • @guptashashwat
    @guptashashwat Рік тому +1

    Nobody taught this approach except you! GOAT

  • @rituparnodas6259
    @rituparnodas6259 Рік тому +1

    class Solution {
    List ls = new ArrayList();
    public boolean findTarget(TreeNode root, int k) {
    if(root == null) return false;
    if(ls.contains(k-root.val)) return true;
    ls.add(root.val);
    return findTarget(root.left, k) || findTarget(root.right, k);
    }
    }

  • @dailydestress6189
    @dailydestress6189 Рік тому +1

    Understood. Wonderful Explanation !!

  • @ayushmandhar9215
    @ayushmandhar9215 Місяць тому

    @8:07
    best expressions

  • @amishasahu1586
    @amishasahu1586 2 роки тому +1

    Understood.
    Thank you Bhaiya for all your efforts.

  • @prajwalgupta1125
    @prajwalgupta1125 Рік тому +2

    Just do an inorder traversal and store it and then just check if there are any two numbers whose sum is ==k using the array

  • @rohannaik4688
    @rohannaik4688 2 роки тому +4

    Hey dude, for the first approach i.e. storing the elements in an array, is taking 2 ms time and 41.1 MB space, and BST iterator technique is taking 8 ms and 47.5 MB space in leetcode, probably the delay is caused because creating a seprarate class and calling the methods is taking more time.

    • @kartikeysharma8904
      @kartikeysharma8904 2 роки тому +5

      don't focus on leetcode time and space they are not accurate

    • @rohannaik4688
      @rohannaik4688 Рік тому

      here you are using stack and in the worst case it will also take O(N) space complexity.

  • @shashankojha3452
    @shashankojha3452 2 роки тому +4

    Great Explanation

  • @fabhacker
    @fabhacker 3 місяці тому +1

    "value badhana hoga"

  • @sandeepbhaskarla6948
    @sandeepbhaskarla6948 Рік тому +1

    Will it work for skew trees??

  • @MitrankShah
    @MitrankShah 2 роки тому +1

    God level explanation for sure!! DAMN!!! Thank you so much!!!

  • @AngadSingh97
    @AngadSingh97 Рік тому

    wow, this was a fantastic solution using the iterator..

  • @karanveersingh5535
    @karanveersingh5535 2 роки тому +3

    Appreciate ur series. 🔥💯

  • @aishwarya8078
    @aishwarya8078 Рік тому +1

    What an explanation
    Hats off to u

  • @rushidesai2836
    @rushidesai2836 Місяць тому

    Brilliant code man, too good!

  • @samanthkrishnamurthy
    @samanthkrishnamurthy 2 роки тому +6

    HI Striver, could you please update the SDE sheet with missing links for code and youtube video link, Many of us are following it for our preparation.

    • @parthsalat
      @parthsalat Рік тому +1

      You'll need to press the youtube thanks button for that

  • @naman_goyal
    @naman_goyal 2 роки тому +3

    Thanks for video best video 💝🎁

  • @kushagraahire1871
    @kushagraahire1871 Рік тому +1

    We can also use a Dequeue in Java

  • @utkarshsaxena7445
    @utkarshsaxena7445 2 роки тому +7

    EASY APPROACH :)
    class Solution{
    public:
    int isPairPresent(struct Node *root, int target)
    {
    vector nums;
    inorder(root,nums);
    return findTarget(nums,target);
    }

    private : void inorder(struct Node* node, vector& nums)
    {
    if (!node) return;
    inorder(node->left, nums);
    nums.push_back(node->data);
    inorder(node->right, nums);
    }


    bool findTarget(vector a, int target)
    {
    for (int i = 0, j = a.size() - 1; i < j;)
    {
    int sum = a[i] + a[j];
    if (sum == target) return true;

    else if (sum < target) i++;

    else j--;
    }
    return false;
    }
    };

    • @Scooby_xD
      @Scooby_xD 2 роки тому

      He already told this approach in the starting of this video ,it s about improving space complexity

  • @prernachaurasia9743
    @prernachaurasia9743 2 роки тому

    thanks a lot for yr help and support...

  • @pulkitjain5159
    @pulkitjain5159 Рік тому

    if we are aloowed to change the data or a tree , we can just fallten these trees and make a doubly linked list from it . , now our taskl is now converted to simply traverse a DLL.

  • @somnathroy102
    @somnathroy102 Рік тому +1

    This cannot get more simple.

  • @neelulalchandani7429
    @neelulalchandani7429 Місяць тому

    👌👌 great explanation

  • @ameydhimte_c5956
    @ameydhimte_c5956 Рік тому +1

    WOW! This is pure Gold!!!

  • @adebisisheriff159
    @adebisisheriff159 6 місяців тому

    Thanks so much Striver!!!!!!!!

  • @ArpitMishra0891
    @ArpitMishra0891 2 роки тому +6

    Can you please make a python code too ? If possible ofcourse ...It will be really helpful

  • @sanskrutishahu517
    @sanskrutishahu517 Рік тому +1

    can we use flattening BST to doubly Linked List and then apply 2 pointer as it would also take O(N) time and O(H) space

    • @Raju_Sharma852
      @Raju_Sharma852 8 місяців тому +1

      You are modifying the tree. Interviewer will not be happy !!

  • @gouravkumar7459
    @gouravkumar7459 2 роки тому

    Easiest Approach, Just amazing

  • @amanbhadani8840
    @amanbhadani8840 2 роки тому +1

    omg omg, absolutely speechless never seen such type of code before,learned a lot.

  • @vamsik1453
    @vamsik1453 Рік тому

    Can the problem be solved in this way? If we iterate over each node 'n', and search for (k - n->val). It takes O(nlogn) time and O(1) space.

    • @pulkitjain5159
      @pulkitjain5159 Рік тому

      haa but yeh to costly hogya na , suppose your tree is a skewed tree so rather than O(nlogn) , you would end up taking O(n*n) solution

  • @astrid_6622
    @astrid_6622 3 місяці тому +1

    why did we need to create objects , why cant we use BSTiterator as function?

  • @codingp110
    @codingp110 2 місяці тому

    really awesome!

  • @b_31mahammadzubair81
    @b_31mahammadzubair81 2 роки тому +3

    Please make a video on printing all paths from root to leaves

  • @suryakiran2970
    @suryakiran2970 2 роки тому

    Objects idea is ellite

  • @pritishpattnaik4674
    @pritishpattnaik4674 2 роки тому +4

    Wow , what a fantastic explanation , u explained and I coded it myself
    My Coding style is a bit different but my solution got accepted in Leetcode
    My Code :
    class BSTIterator{
    public:
    stack st;

    BSTIterator(TreeNode *root, int flag){
    if (flag == 1){
    while (root != NULL){
    st.push(root);
    root = root->right;
    }
    }
    else {
    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;
    }

    int before(){
    TreeNode *currNode = st.top();
    st.pop();
    if (currNode->left != NULL){
    TreeNode *temp = currNode->left;
    while (temp != NULL){
    st.push(temp);
    temp = temp->right;
    }
    }
    return currNode->val;
    }
    };
    class Solution {
    public:
    bool findTarget(TreeNode* root, int k) {
    if (root == NULL) return false;
    BSTIterator l(root, 0); //next
    BSTIterator r(root, 1); //before

    int i = l.next();
    int j = r.before();

    while (i < j){
    if (i + j == k) return true;
    else if (i + j < k) i = l.next();
    else j = r.before();
    }
    return false;
    }
    };

    • @atifhu
      @atifhu Рік тому +1

      striver se better tera code lag rha

    • @pritishpattnaik4674
      @pritishpattnaik4674 Рік тому

      @@atifhu thanks for the compliment ❤️ , but Striver is God

  • @sejalbansal7859
    @sejalbansal7859 Рік тому +2

    class Solution {
    public:
    stack largest;
    stack smallest;
    void leftiterator(TreeNode* root, stack &smallest){
    while(root){
    smallest.push(root);
    root=root->left;
    }
    }
    void rightiterator(TreeNode* root, stack &largest){
    while(root){
    largest.push(root);
    root=root->right;
    }
    }
    bool findTarget(TreeNode* root, int k) {
    leftiterator(root, smallest);
    rightiterator(root, largest);
    while(largest.top()!=smallest.top())
    {if(smallest.top()->val+largest.top()->val==k)
    return true;
    if(smallest.top()->val+largest.top()->val>k){
    TreeNode* x= largest.top();
    largest.pop();
    rightiterator(x->left, largest);
    }
    else{
    TreeNode* x= smallest.top();
    smallest.pop();
    leftiterator(x->right, smallest);
    }}
    return false;
    }
    };

  • @UECAshutoshKumar
    @UECAshutoshKumar Рік тому +1

    Thank you sir

  • @flanker53
    @flanker53 Рік тому

    why is while(i < j ) working ? since i and j will be values and not index ?

    • @piyushacharya7696
      @piyushacharya7696 Рік тому

      I suppose, because I initially points to the very smallest value and j points to the very largest value. When I crosses j, it means that it has crossed all of the values that could add up to the answer.

    • @varunaggarwal7126
      @varunaggarwal7126 Рік тому

      BST property, all left are smaller than right

  • @ShubhamGupta-po3ul
    @ShubhamGupta-po3ul 2 роки тому +4

    can we convert this bst into dbll and then 2 pointer ?

  • @pranavsharma7479
    @pranavsharma7479 2 роки тому +1

    damm, how could i think that if i have not seen the solution, i only thought for O(n) and O(n)

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l 4 місяці тому

    Thank you Bhaiya

  • @varunaggarwal7126
    @varunaggarwal7126 Рік тому +1

    1st approach:
    public class Solution {
    public bool FindTarget(TreeNode root, int k) {
    List inorder = new List();
    Inorder(root, inorder);
    int i=0, j=inorder.Count-1;
    while(j>i){
    if(inorder[i]+inorder[j]>k){
    j--;
    }
    if(inorder[i]+inorder[j]i){
    i++;
    }
    if(inorder[i]+inorder[j]==k&& j>i){
    return true;
    }
    }
    return false;
    }
    public static void Inorder(TreeNode root, List inorder){
    if(root==null){
    return;
    }
    Inorder(root.left, inorder);
    inorder.Add(root.val);
    Inorder(root.right, inorder);
    }
    }

  • @bhaveshkumar6842
    @bhaveshkumar6842 2 роки тому

    Thank you, Striver!!!

  • @Lalit_Shirsath
    @Lalit_Shirsath 2 роки тому +2

    is this last video of the series

  • @rishabhkumar8115
    @rishabhkumar8115 2 роки тому

    Thankx for this valuable series

  • @ritikshrivastava9442
    @ritikshrivastava9442 Рік тому +1

    i am little confuse how we can do next() and before() in just one stack?

    • @piyushacharya7696
      @piyushacharya7696 Рік тому

      We are creating two different object of the same class.

  • @BharatiSubramanian99217
    @BharatiSubramanian99217 Рік тому

    This algorithm - What a beauty! 😍

  • @health_pe_charcha
    @health_pe_charcha 2 роки тому +2

    doing by the help of vector and 2 pointers is wrong?

    • @aditisrivastava6499
      @aditisrivastava6499 2 роки тому +1

      Its not wrong but using BST iterator is the most optimized solution for this problem as it uses space complexity of O(H).

    • @blurrybrush1010
      @blurrybrush1010 2 роки тому

      that has space complexity of O(n) while optimized version has O(logN)

  • @siddharthpaul3704
    @siddharthpaul3704 2 роки тому

    Thanks Raj for the Tree series.

  • @rohanyelpale3365
    @rohanyelpale3365 2 роки тому

    If we have two trees and we need to count the total no of pairs whose sum is X and pair should be form using one node from one tree and another node from another?

  • @beginnertopro7265
    @beginnertopro7265 Рік тому

    bhaiya ap hindi bhi bola karo bich bich me
    bhaut achha lagta haii

  • @sailendrapavan3475
    @sailendrapavan3475 2 роки тому

    Brilliant solution

  • @abhinanda7049
    @abhinanda7049 3 місяці тому

    understood

  • @ParasLeela
    @ParasLeela Рік тому

    Ty

  • @solarsystem9156
    @solarsystem9156 Місяць тому

    Also recursive solution:
    class Solution {
    public:
    bool finding(TreeNode* root, int k){
    if(root==NULL) return false;
    if(root->val == k) return true;
    if(k < root->val) return finding(root->left, k);
    if(k > root->val) return finding(root->right, k);
    return false;
    }
    bool check(TreeNode* temp, TreeNode* root, int k){
    if(root==NULL) return false;
    // if(root->val == k) return true; -> causing error in 3rd TC
    int rem = k - root->val;
    if(rem!=root->val and finding(temp, rem)) return true;
    if(check(temp, root->left, k) or check(temp, root->right, k)) return true;
    return false;
    }
    bool findTarget(TreeNode* root, int k) {
    if(root==NULL) return false;
    return check(root, root, k);
    }
    };

  • @aswinkrishna204
    @aswinkrishna204 2 роки тому

    lovely, sir love u a lot, sir learning a lot from your lecture

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 Рік тому +1

    awesome literally just awesome

  • @HarshitMaurya
    @HarshitMaurya 2 роки тому +1

    Bhaiya why space is O(h) why not O(n) we are storing all the nodes of BST in Stcak right ?

    • @FusionArcs
      @FusionArcs 2 роки тому +1

      No, we are not. At any point in time, only the O(H) nodes can be present in the stack.
      Please do a dry run and check if your stack overflows the height of your tree

  • @lavanyaprakashjampana933
    @lavanyaprakashjampana933 Рік тому

    we love your content and we love you...🖤

  • @jaiminsolanki5478
    @jaiminsolanki5478 2 роки тому

    TYSM Brother!!!

  • @vaibhavrai7042
    @vaibhavrai7042 2 місяці тому

    How are we ensuring that we do not consider the same element twice?

  • @Anonymous-uj3jx
    @Anonymous-uj3jx 2 роки тому

    Understood thanks :)

  • @LokeshSharma-hm5jz
    @LokeshSharma-hm5jz 11 місяців тому

    understood. thanks.

  • @harshitjaiswal9439
    @harshitjaiswal9439 6 місяців тому

    understood.

  • @singhmanish4540
    @singhmanish4540 Рік тому

    Woooooooow Amazing explaination 😍😍

  • @noobcoder5383
    @noobcoder5383 2 роки тому +2

    sira approach

  • @sandeepbhaskarla6948
    @sandeepbhaskarla6948 Рік тому

    Will it work for tree with 1, 2,3,4,5 because first we willtake (5,4,3,2,1) then (5 ) for other . when we want sum as 7 we do like . 1+5 ans then 2+5 its ok in that case stack modifies as (5,4,3) and (4,3,2,1) casue 5 pops out. then check again (4+5) > 7 pop out from 2nd stack (5,4,3) and (3,2,1) and again (5+3>7) pop out from 2nd (5,4,3) and (2,1) we only pop from 2nd stack not the one with max right . in that case again (5+2) again 7 same result. so we pop both . (4,3) and (1) . we are missing one more case of 4+3 right in this ?