Binary Lifting (Kth Ancestor of a Tree Node)

Поділитися
Вставка
  • Опубліковано 29 бер 2021
  • Tutorial on binary lifting (also called jump pointers). We find k-th ancestor of a node in O(log(N)). Problem link leetcode.com/problems/kth-anc...
    Final code github.com/Errichto/youtube/b...
    Coding live streams - / errichto
    FAQ - github.com/Errichto/youtube/w...
    Subscribe for more educational videos on algorithms, coding interviews and competitive programming.

КОМЕНТАРІ • 199

  • @deepeiton6112
    @deepeiton6112 3 роки тому +103

    The perfect video to find before going to bed :)

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

      Finally I meet someone who feels the same... Even before going to bed, I can understand this guy's explanations in a short time, what a legend!

    • @sanyamjha5796
      @sanyamjha5796 Рік тому +4

      Aah, that connection when you feel the exact same way as a complete stranger on UA-cam..... The Internet did break many walls

  • @sharinganuser1539
    @sharinganuser1539 3 роки тому +61

    Thank god...I'm trying to understand this for a week now...

    • @Errichto
      @Errichto  3 роки тому +86

      I hope it doesn't take another week with my video :|

    • @ani68
      @ani68 3 роки тому +9

      @@Errichto it will surely not....😊

    • @deepeiton6112
      @deepeiton6112 3 роки тому

      @@Errichto if I want to find minimum number of numbers(power of 2) that sum upto some k. Does this approach hold?

    • @user-qm4jh2oj6f
      @user-qm4jh2oj6f 3 роки тому

      @@deepeiton6112 Yes, this idea is used in LCA. If you want, you can ask something particular and I will answer you.

    • @user-qm4jh2oj6f
      @user-qm4jh2oj6f 3 роки тому

      @@deepeiton6112 As far as I understood, you asked, If it's true, that any number can be represented as the number of sums of two. The answer is Yes, you can find this powers of two greedy. Go from bigger powers of two to lower.
      Example: 49 = 32 + 16 + 1, or 90 = 64 + 16 + 8 + 2.
      Good way to do it in C++:
      vectorpowers;
      int num; cin >> num;
      for (int i = 30; i >= 0; i--){
      if(num - (1 = 0){
      num -= (1

  • @ani68
    @ani68 3 роки тому +35

    I always tried with O(n) way....thanks for this O(logN) way.....nice explanation....👍👍

  • @vineethkumar8132
    @vineethkumar8132 3 роки тому +44

    I'm a beginner at CP but still was able to understand much of this, Thank you for such an amazing explanation Erichto ❤️

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

    These videos are gold mines, an ultimate treasure. Loved it.

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

    Very thanks for the clear explanation. I understood it again very well. Thanks a lot, Errichto!

  • @shauryagautam5143
    @shauryagautam5143 3 роки тому +1

    Thanks Errichto, just cz you have made the video, I gt to know a new concept I never heard about! Keep making such videos!! Helps a lot!!

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

    Thank you Errichto! I'm a new subscriber to the channel and you've really helped me a lot! Your explanations are far more better than my mentors in school. TYSM!

  • @saranshdabas4223
    @saranshdabas4223 3 роки тому +1

    Always love your explanations, the best stuff out there.

  • @ANKITVERMA-fl1zn
    @ANKITVERMA-fl1zn 3 роки тому +11

    Yet Again Another Life Saver Video Lecture, I will share this to my friends Thanks a lot!

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

    Incredibly chilly vibe, good explanation... overall great video, thanks!

  • @bhaskar08
    @bhaskar08 3 роки тому +12

    I like to add just another node (N+1) above the root and parent of (N+1) is itself. now at every query if the ancestor (N+1) return -1

  • @anonymous3419
    @anonymous3419 3 роки тому +1

    Thank you sir, watching your video reminds me a lot when i participated in Math Contest...

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

    thanks for all of this insane useful thing for CP
    hope you have more video in the future

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

    Simply amazing, Thanks Errichto.

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

    Thank you errichto keep doing videos about CP_topics which are hard to understand.

  • @srishtikdutta8946
    @srishtikdutta8946 3 роки тому +3

    Great, please bring more such videos.

  • @AmitSharma-yb9vc
    @AmitSharma-yb9vc 3 роки тому

    Now, It's looking so easy. Thank you.

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

    Nice explanation . Binary lifting doesn't seem tough anymore :)

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

    Extremely well presented, thanks

  • @GGxEpsilon
    @GGxEpsilon 3 роки тому +7

    Thanks for uploading this 😊

  • @Squirrelschaser
    @Squirrelschaser 3 роки тому

    yo this vid came in clutch been trying to understnad this problem.

  • @jdragon8184
    @jdragon8184 3 роки тому +1

    who is here after edu 110 div 2 , thanks a lot i solved E after watching this

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

    this guy learned english, and computer science and how to explain things clearly and put it all on youtube for free so us dumb people can learn, what a legend

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

    Thanks, just realized this was the hardest leetcode question in Tree segment, helped a lot...... One small addition in the last part is that we don't need to calculate depth if we just check that node is -1 in each iteration
    code -
    for i in range(self.log):
    if k & (1

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

      you are right, I also implemented it this way, but he said that he didn't want to add extra steps in the pre-calc to make this work and preferred the depth way!

  • @Dontpushyour_luck
    @Dontpushyour_luck 9 місяців тому

    nice explanation. as a beginner, i was able to understand easily

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

    thank you very much for this amazing tutorial

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

    Thanks for the awesome explanation

  • @user-pi2zd4xj8z
    @user-pi2zd4xj8z 3 місяці тому

    Just awesome, i hv gone through whole lot of comments, and the coders here are awesome.. great place to Meetup.

  • @AmitShukla-pw5hg
    @AmitShukla-pw5hg 2 роки тому +1

    Excellent material for CP

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

    What a video man..... Lovely... I really enjoyed and had fun watching it...... #LoveCoding

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

    Beautiful explanation

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

    Thanks for such good content 🙌

  • @thetester8371
    @thetester8371 3 роки тому +13

    Cool lecture man.
    I used to think there was some sort of relation between binary search and binary lifting. Well there indeed is a relation, but not exactly. I still kinda hate how some chinese contestants use the word "binary search" and "binary lifting" interchangeably, although........I sort of understand why, especially if you into a habit of writing binary search using for loops instead of while .

    • @Errichto
      @Errichto  3 роки тому +20

      There is a bigger similarity if you implement binary search by using powers of two. Say that you are searching in range [L, R].
      for(int i = 19; i >= 0; i--) { int mid = L + (1

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

      @@Errichto I love you

  • @rishijha9860
    @rishijha9860 3 роки тому +1

    Very nicely explained 🙂

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

    Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

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

    They added the test case you were talking about nodes violating the condition parent[i]

  • @itz_me_imraan02
    @itz_me_imraan02 Рік тому +4

    The same code is giving WA in test case [4,[-1,2,3,0]], [2,3], [2,2] , [2,1]
    U considered the nodes to be in increasing order from top to bottom, dats why it failed when the nodes are in decreasing order..

  • @vishnusingh9590
    @vishnusingh9590 3 роки тому +9

    @Errichto - At 11:21 : You say "And there's this condition about parents which is also quite convenient". I don't think that's the condition you mean. The condition at 11:21 is parent[ i ] < n, which is NOT the same as : parent[ i ] < i

  • @artistic__08
    @artistic__08 7 місяців тому

    All this time op was like - "This is so simple".
    Thanks for the explanation.

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

    Thank you Errichto

  • @amartyasarkar8631
    @amartyasarkar8631 3 роки тому +1

    Awesome explanation

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

    We would be grateful if you would ever make a proper series, or course for competitive programming..
    From medium to very advanced methods concepts to solve hard competitive programming problems...

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

    Awesome explanation.

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

    I think leetcode has changed the question a bit now, now it is not necessaary that parent.value < node.value
    what I did to solve this is find the order in which nodes appear so like using bfs and then applied the same
    // code
    class TreeAncestor {
    public:
    vector bfs(vector& arr,int i){
    vector res, visited(arr.size(),0);
    queue q;
    q.push(i);
    while(q.empty() == false){
    int len = q.size();
    while(len--){
    int node = q.front();
    q.pop();
    visited[node] = 1;
    //add to res
    res.push_back(node);
    for(int j: arr[node]){
    if(visited[j]) continue;
    q.push(j);
    }
    }
    }
    return res;
    }
    int LOG = 20;
    vector dp;
    TreeAncestor(int n, vector& parent) {
    //make tree here
    vector arr(n);
    for(int i=1;i

  • @gauravupreti9340
    @gauravupreti9340 8 місяців тому

    Thanks for the to the point explanation

  • @ilikememes9052
    @ilikememes9052 9 місяців тому

    @Errichto 15:38 you dont need to change any condition for log calculation, All you have to do is to change the iteration in loop from j=0;j

  • @tharunchowdary14
    @tharunchowdary14 3 роки тому

    please do this kind of videos, Thank you!

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

    powers of 2 technique is also used in BIT(Binary Indexed Tree)

  • @pwshen5046
    @pwshen5046 8 місяців тому

    thanks its really clear and useful!

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

    Thanks for the explanation really helped a lot ,
    Now As the condition is parent[i] < n , loops order will get changed and we can avoid depth track too
    int[][] up;
    int log = 17;

    public TreeAncestor(int n, int[] parent) {


    up = new int[n][log];
    //assuming 0 is the root node
    parent[0] = -1;


    //setting up first ancestor
    for( int i = 0 ; i < n ; i++)
    up[i][0] = parent[i];


    //setting up other ancestors
    for( int j = 1 ; j < log ; j++)
    {
    for( int v = 0 ; v < n ; v++)
    {
    if(up[v][j-1] == -1)
    up[v][j] = -1;
    else
    up[v][j] = up[ up[v][j-1] ][j-1];
    }
    }


    }

    public int getKthAncestor(int node, int k) {

    for(int i = 0 ; i < log ; i++)
    {
    if(((1

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

      Can you please explain to me why this code only solving cases where parent[i]

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

    best explanation of the world

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

    Finally he remembered that he has a youtube channel. Thanks a ton.

  • @AnuragSingh7
    @AnuragSingh7 Рік тому +4

    For case where we need to return "-1" : How about for every query we can calculate both Kth and (K-1)th ancestor. If they are equal we return -1 else we return Kth ancestor

    • @jonathanarthuritoaldisinag573
      @jonathanarthuritoaldisinag573 11 місяців тому

      I think you can't do that if k == 1. if k == 1, then we're gonna check the ancestor with distance 0 and 1. errichto's implementation itself i think it is unsuited to find the ancestor with distance 0. but if you make a if else statement, i think you can...

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

    Perfect, Made my day.

  • @sandeepradhakrishnapadhi6366
    @sandeepradhakrishnapadhi6366 3 роки тому +1

    Thankyou..Sir,can you please make stream specifically related to mathematical background..

  • @akanshkumar2876
    @akanshkumar2876 3 роки тому +1

    Thanku Errichto🙃

  • @praveenj3112
    @praveenj3112 3 роки тому +10

    Superb solution. initially hard to understand

  • @mradultiwari5820
    @mradultiwari5820 3 роки тому +1

    🙏🏻🙏🏻got a couple of new thoughts 💛

  • @eng.khalid9763
    @eng.khalid9763 3 роки тому +1

    Thank you..
    could you please make a video on how to code branch and bound with the example on travelling salesman problem, knapsack problem or any other example.
    I want to know how to find the next children of the parent and how to get the final solution

  • @sharadsharma3176
    @sharadsharma3176 3 роки тому +10

    Waiting for game theory related video, sir.🥺

  • @teddq7210
    @teddq7210 3 роки тому

    Happy Easter ❤️

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

    Video request: string algorithms (KMP, Manacher). They don't occur often on CF but do on ICPC and I would like a nice resource (there aren't any nice video resources on these topics).

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

    thank you for this video;

  • @MrDivad006
    @MrDivad006 3 роки тому +3

    More leetcode problems pleasee. Just go crazy and solve all leetcode problems and put them into a playlist

    • @Errichto
      @Errichto  3 роки тому +3

      that's a lot of videos :|

    • @MrDivad006
      @MrDivad006 3 роки тому

      @@Errichto That's true. Normal mortals can't do it. But someone like you can just rush through most problems, you can use your strengths to the fullest and bring value to the world that others can't. Just read a problem, state your thoughts and approach, code, next problem.

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

      @@MrDivad006 nah, rather have him do lectures like these and you can try solving all the problems with the concepts he teaches

  • @ruslankushnir761
    @ruslankushnir761 3 роки тому +1

    Hi Errichto, thank you very much for your tutorials, please consider possibility to make background of your videos little less black, for example blue dark or silver dark to make them more neural, I think that in that case watching your videos will be less stressful for the eyes, thanks

    • @Errichto
      @Errichto  3 роки тому +1

      Dark gray seems neutral enough, I think.

    • @ruslankushnir761
      @ruslankushnir761 3 роки тому

      @@Errichto ohhh, I watched several yours videos in parallel, black background is present on your first tutorials. Good luck in Code Jam competition

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

    Superb video Errichto, would you be interested in making some String algorithms videos? Suffix array in NlogN, Ukkonen, Manacher, Hashing(This is going to be super informative, if you include the anti-hashing test breaks that were mentioned on codeforces a few years ago when you use overflow), Suffix Trie and use cases, Compressed Trie?
    This will add so much more value to your already amazing channel!:) Much thanks!

  • @tritranminh2808
    @tritranminh2808 3 роки тому +1

    Thank you so much.

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

    Thanks for the wonderful lecture.
    But I am a bit confused about the way depth[v] and up array have been computed in the leetcode problem, it is never mentioned that parent[v] < v. If this condition is not true then result should be incorrect. Right? Or I am missing something.

  • @RaoVenu
    @RaoVenu 3 роки тому +1

    @Errichto At 16:30, line 30, you use
    if (k & (1

  • @satyambhardwaj2289
    @satyambhardwaj2289 3 роки тому +1

    appreciate it! Thanks

  • @CristhianR51
    @CristhianR51 3 роки тому +14

    I understand that if "parent[i] < i", then you can safely compute the parent array for each V in increasing order.
    However on leetcode it states that "parent[i] < n", which is a different thing, no?
    Thanks for the video!

    • @Errichto
      @Errichto  3 роки тому +24

      Oh, good catch. I've misread the condition as "parent[i] < i". Then my solution shouldn't work with the current order of for-loops and the test data is apparently weak.

    • @jahnvikumari318
      @jahnvikumari318 2 роки тому +14

      @@Errichto Hey, thanks I have contributed a test case to Leetcode so that this fails. Sorry but now your code also fails.

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

      @@jahnvikumari318 Cheers for that!

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

      @@jahnvikumari318 🥲

    • @Dontpushyour_luck
      @Dontpushyour_luck 9 місяців тому

      you are right. I used a visited array and called another function to compute for a node if it is not visited yet. i was confused on how his code passed the test cases. now i understand that test cases were weak in the past

  • @josephwong2832
    @josephwong2832 3 роки тому +1

    nice job

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

    When we exchange the for loops, (where the LOG for loop is before) will work in both cases (independent of the value/order of nodes) while calculating the up vector?

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

    Thanks a lot.

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

    Add this video to the Edu playlist please

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

    How depth[v]=depth[parent[v]]+1????
    This holds if depth[parent[v]] is already computed which is not always true.

  • @user-zl7xr5bo2r
    @user-zl7xr5bo2r 3 роки тому +1

    Sir, May I have any advice on How and when to turn my kids to Math from your perspective ? They are 2yo, and I’m preparing now)

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

    Thanks !!

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

    nice video

  • @nj9362
    @nj9362 3 роки тому

    What hardware/software do u use to teach and write?

  • @Aditya-rp1lr
    @Aditya-rp1lr 3 роки тому +1

    waiting for sparse table lecture

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

    Hi, you mentioned since input n can be upto 50k, quadratic runtime won't work. What is the limit of input till which quadratic would work and why? Thanks!

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

    Thanks pls do graphs dfs and bfs.

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

    Can you please explain to me why this code only solving cases where parent[i]

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

    Errichto your code isn't working for this problem, you have to use the dfs method to do preprocessing.

  • @VK-oq6cb
    @VK-oq6cb 3 роки тому +2

    Hey Errichto , What can we do
    ..if we have two types of quries in which one query type is we can add or delete leaf node in tree and other type return Kth ancestor !?

    • @Errichto
      @Errichto  3 роки тому

      Easy: just compute all log(N) needed ancestors when adding a new leaf. No need to do anything when removing a leaf.

    • @VK-oq6cb
      @VK-oq6cb 3 роки тому

      @@Errichto thanks a lot :-)

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

    2:38 I think segment tree is divide and conquer approach ??

    • @Errichto
      @Errichto  3 роки тому +1

      Yeah, in some way it is. What I meant is that segment trees and fenwick trees are often implemented for perfect powers of two.

  • @dst8676
    @dst8676 3 роки тому +1

    what is software you used to present

  • @0chunhui
    @0chunhui 3 роки тому +1

    why could you use node that has not been calculated? I mean this part: for(int v=0; v

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

    I´m trying to solve a similar problem but I need to calculate the sum of a given node and a number of parents ex: node 2 and 5 parents and l have to return the sum of the values of that nodes. Any ideas of how can calculate the sum if i have the table with the k ancestros

  • @naveen3192
    @naveen3192 3 роки тому

    What's the tool you use to draw man?

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

    Very Nice Explanation 😍.
    I think you calculated depth in wrong manner
    consider this case:
    ["TreeAncestor","getKthAncestor"]
    [[6,[-1,2,3,4,5,0]],[1,4]]
    depth array according to code will be [0,1,1,1,1,1] but it should be [0,5,4,3,2,1]
    and for node = 1, 4th ancestor should be 5 but it will give -1 as depth is wrong.

  • @5590priyank
    @5590priyank 3 роки тому

    Can we use fenwick tree trick for jumping to parents for finding kth ancestor?
    currently, if k = 21, we are jumping like 1 then 4 then 16. How about we jump in reverse like 16 then 4 then 1?
    we can use following to move to 16 from 21:
    int nextJump = k & -k;
    then
    k -= nextJump; // this makes k = 5 again
    and we repeat same.

    • @Errichto
      @Errichto  3 роки тому +1

      What you described is another way to get the binary representation of K. It's just commonly used in Fenwick trees.

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

    Is the github solution fine? it gives some error on one of the leetcode estcases

  • @naklecha
    @naklecha 3 роки тому

    Instead of depth can we check if node == up[node[j]] return -1

    • @Errichto
      @Errichto  3 роки тому

      Are you trying to check if node is the root? I don't see how that helps.

    • @naklecha
      @naklecha 3 роки тому

      I meant instead of depth. We could go up the tree and if we get the condition we return -1.

  • @ritikraj26_
    @ritikraj26_ 10 місяців тому

    The condition of the leetcode problem has changed. Now you will need to swap the loops. XD

  • @yuvarajanm2059
    @yuvarajanm2059 3 роки тому +1

    Bro I have a doubt , while debuging a program in vscode which uses array of string. I want to see all the elements while debuging, but it does not show like that. I need yr help bro. I stucked in that for 3 days..please if anyone knows help me.

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

    Why are you using log(n) instead of log(height of tree) in your implementation ? The n (number of nodes) must be larger than height.

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

      Log2(n)+1 will provide the height of tree only, you can even use this condition to get you log value and it will work.

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

      @@sudhanshukumarroy7018 Did I understand correctly that n is a height of the tree in a worst case scenario ?

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

      That's why I suppose for worst case tree we will get higher order ancestors rather than getting -1 too quickly in a binary tree like tree.
      It is supposed like log value is the value whose 2^LogValue will provide highest possible ancestor that can exist.

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

    Though the provided solution does look correct, it doesn't pass 5 out of 15 test cases on leetcode :(