Find merge point of two linked list

แชร์
ฝัง
  • เผยแพร่เมื่อ 26 ส.ค. 2024
  • In this lesson, we have solved a famous programming interview question - finding merge point of two linked list. We have written a C++ implementation.
    See source code here:
    gist.github.co...
    See series on linked list here:
    • Introduction to linked...
    See series on time complexity here:
    • Time complexity of a c...
    About sets:
    www.cplusplus.c...
    You may also like/follow us on Facebook/Twitter:
    / mycodeschool
    / mycodeschool

ความคิดเห็น • 121

  • @manojpandey7517
    @manojpandey7517 4 ปีที่แล้ว +39

    Even if there are oceans of content available online on a same topic, mycodeschool always stands out of them. It's kinda sad why you guys stopped making more videos.

    • @pulkitsharma7105
      @pulkitsharma7105 4 ปีที่แล้ว +6

      The founder of mycodeschool died in an accident 5 years ago

    • @sheruloves9190
      @sheruloves9190 4 ปีที่แล้ว +1

      @@pulkitsharma7105 Fuck.. was that the one delivering dsa topics?

    • @PrathamGupta2408
      @PrathamGupta2408 4 ปีที่แล้ว +1

      RIP

    • @merohan619
      @merohan619 3 ปีที่แล้ว +1

      @@sheruloves9190 yes, he was a national level coder.

    • @saketkumar5884
      @saketkumar5884 3 ปีที่แล้ว

      @@sheruloves9190 No

  • @lukestumpf1524
    @lukestumpf1524 4 ปีที่แล้ว +3

    Make sure to set d = -d in the swap section of code so if you need to swap you actually go through all of the values you need. Great video!

  • @swami2672
    @swami2672 3 ปีที่แล้ว +2

    Thanks for the video.
    Instead of swapping, just traverse the larger linked list in advance.
    CODE:
    /**
    Definition for singly-linked list.
    class ListNode {
    public int val;
    Public ListNode next;

    ListNode(int x){
    val = x;
    next = null;
    }
    }
    */
    public class MergePoint {
    public int getLength(ListNode a) {
    int count = 0;
    ListNode temp = a;
    while (temp != null) {
    count++;
    temp = temp.next;
    }
    return count;
    }
    //Traverse the larger list by d times
    //So both the starting points of the list will come on the same track
    //Starting point of b will be now 40 and not 200
    public ListNode traverseD(ListNode a, int d) {
    for (int i = 0; i < d; i++)
    a = a.next;
    return a;
    }
    public ListNode getIntersectionNode(ListNode a, ListNode b) {
    int a_length = getLength(a);
    int b_length = getLength(b);
    int d;
    //Whoever is larger will traverse in extra
    if (a_length > b_length) {
    d = a_length - b_length;
    a = traverseD(a, d);
    } else {
    d = b_length - a_length;
    b = traverseD(b, d);
    }

    //Now a and b are on the same track
    //100 on A and 40 on B
    while (a != null && b != null) {
    if (a == b)
    return a;
    a = a.next;
    b = b.next;
    }
    //If there are no merging points
    return null;
    }
    }

  • @krsingh.shubham
    @krsingh.shubham 3 ปีที่แล้ว +5

    mah-god, after moving through so many tutorials for this problem, none explained me with this much clarity.

    • @ytg6663
      @ytg6663 2 ปีที่แล้ว

      Ok. Thank me later

  • @arjitaagrawal270
    @arjitaagrawal270 3 ปีที่แล้ว +1

    Great explanation..the practical example made it even more interesting and easy to understand. Such examples are appreciated

  • @harikishanpuvvala5973
    @harikishanpuvvala5973 6 ปีที่แล้ว +2

    This video is good. With an exception that it is mistyped as 80 instead of 30 in the list A for the node 140.

  • @ritikashishodia3829
    @ritikashishodia3829 3 ปีที่แล้ว

    great explanation i am solved this problem at hacker rank I do not understand what is actually merge point ....hacker rank give mycodeschool channel link ..then finally i understand what is merge point.

  • @subham-raj
    @subham-raj 5 ปีที่แล้ว +2

    *If you use HashSet then time-complexity would be O(m + n) and Space-complexity would be either O(n) or O(m) depends on which linked list data you would like to store in the HashSet.*

    • @subham-raj
      @subham-raj 5 ปีที่แล้ว +1

      FOUND ONE MORE COOL SOLUTION:
      int FindMergeNode(Node headA, Node headB) {
      Node currentA = headA;
      Node currentB = headB;
      //Do till the two nodes are the same
      while(currentA != currentB){
      //If you reached the end of one list start at the beginning of the other one
      //currentA
      if(currentA.next == null){
      currentA = headB;
      }else{
      currentA = currentA.next;
      }
      //currentB
      if(currentB.next == null){
      currentB = headA;
      }else{
      currentB = currentB.next;
      }
      }
      return currentB.data;
      }

    • @nikhilnikhil3517
      @nikhilnikhil3517 3 ปีที่แล้ว

      @@subham-raj how do you ensure that this code runs for the linked lists having no intersection

  • @TheKundan11
    @TheKundan11 10 ปีที่แล้ว +3

    Nice explanation !!!! And good approach of solving a problem first in brute force and then going on optimizing it .

  • @sunilvurity
    @sunilvurity 10 ปีที่แล้ว +7

    To decide the longer list you are performing a swap , but you can also do without swap using lengths of both lists
    if (lengthOfB > lengthOfA)
    //Move B till lengthOfB - lengthOfA;
    else if (lengthOfB < lengthOfA)
    //Move A till lengthOfA - lengthOfB;

    • @subham-raj
      @subham-raj 5 ปีที่แล้ว

      Bro you have to swap the head pointers as you might traverse the wrong list. Think about it.

  • @avnishgupta8731
    @avnishgupta8731 9 ปีที่แล้ว +4

    sir in this there is error at 4:40 in the link list A the 2 nd node which has data value 6 has the value in the next pointer 30 and not 80. plz correct it

  • @rajasekharkalakangeri1708
    @rajasekharkalakangeri1708 6 ปีที่แล้ว

    finding length ofeach linked list also takes some time here.
    Here is my approach
    1. Insert all the nodes of linked list A to a simple array (X)
    2. Insert all the nodes of linked list B to a simple array (Y)
    3. Start a loop to fetch from both the arrays starting from the last element, every time nodes from both arrays will be equal. At an instance nodes from arrays go unmatch, break the loop and return the previous instance as the output.

  • @chitrasomasingh5388
    @chitrasomasingh5388 10 ปีที่แล้ว +8

    i didnt understand the condition:
    if(addresses.find(A)!=addresses.end())
    what is the use of addresses.end overhere ??

    • @mycodeschool
      @mycodeschool  10 ปีที่แล้ว +4

      Chitrasoma Singh There is this concept of iterators in standard template library of C++.. Go through this - community.topcoder.com/tc?module=Static&d1=tutorials&d2=standardTemplateLibrary

  • @yasser_hussain
    @yasser_hussain 6 ปีที่แล้ว

    A set implemented as hash has O(1) insert, delete, find time complexity. So even for Hashset solution we will get O(m+n) time albeit space complexity will be O(n).

    • @codingcart
      @codingcart 4 ปีที่แล้ว

      th-cam.com/video/WcOdcUHOA1M/w-d-xo.html

  • @jamesward2946
    @jamesward2946 6 ปีที่แล้ว +1

    This is a great tutorial. Thanks for the corner cases explanation at the end :).

    • @codingcart
      @codingcart 4 ปีที่แล้ว

      th-cam.com/video/WcOdcUHOA1M/w-d-xo.html

  • @Shree__98
    @Shree__98 4 ปีที่แล้ว

    Sooo well explained..🎉 You deserve appreciation 👏

  • @jaysahu357
    @jaysahu357 6 ปีที่แล้ว

    very very nice you teach me many thing in one video about how to optimize the code,thank a lot

  • @s20_d84
    @s20_d84 10 ปีที่แล้ว +1

    Nice explanation with real tym example .. I liked this tutorial ... keep it up :)

  • @suguruchhaya3194
    @suguruchhaya3194 3 ปีที่แล้ว

    Your video was so damn easy to understand. RIP and thank you.

  • @ChandraShekhar-by3cd
    @ChandraShekhar-by3cd 4 ปีที่แล้ว

    Your explanation was Perfect!..Please upload more videos

  • @sidddcloud
    @sidddcloud 5 ปีที่แล้ว +1

    Also you can join the tail of both list. Then find the starting point of loop

    • @prateektewary7526
      @prateektewary7526 3 ปีที่แล้ว

      For that you will require a doubly linked list to traverse back from tail.

  • @sriramiyer9840
    @sriramiyer9840 4 ปีที่แล้ว +2

    in the last approach, d should be set equal to abs(n-m), i.e.,
    d = abs(n-m);
    as the value of n-m can be negative too

    • @naveendara8646
      @naveendara8646 4 ปีที่แล้ว

      Check the if statements
      It has a d=m-n statement

  • @CSshreyas
    @CSshreyas 8 ปีที่แล้ว

    what if the liked lists are modified in way that they have some diverging point after they merge? and the lists are of different length? something like two trains have just few common stations Train 1 stops at station A -> B -> C -> D -> E -> F. Train 2 stops at station H -> I -> C -> D -> J -> K -> L -> M

    • @zoltanie
      @zoltanie 7 ปีที่แล้ว

      then it's not a linked list!

  • @prabhu2263
    @prabhu2263 6 ปีที่แล้ว

    What happens in the following cases:-
    1. If the common nodes are in the starting of both linked lists? like L1 - 1,2,3,4,5,6,7,8. L2 - 1,2,3,9,10,11,12.
    2. If both the lists has same length?. Then we end up again in the equivalent method of brute force.

    • @pymondo1147
      @pymondo1147 5 ปีที่แล้ว

      1. It seems in singy linked list we can never have node pointing two address . So this is invalid. It will be unique memory for both the lists.

    • @divyamsh2115
      @divyamsh2115 5 ปีที่แล้ว

      if the first node itself is matching then return the first node,else follow this approach!

  • @redraushan
    @redraushan 4 ปีที่แล้ว

    I was banging my forehead for hours thinking how could two separate linked list can have a merge point, thank god I finally am here.

  • @TheAbhijeetidiot
    @TheAbhijeetidiot 10 ปีที่แล้ว

    please upload some lectures on conditional statements and loops, arrays, functions and storage classes.

  • @FitnessChaos
    @FitnessChaos 3 ปีที่แล้ว

    Good explanation but the optimal solution is not dynamic. You actually don’t know which of the A or B nodes is bigger so you have to check and iterate for that too

  • @blasttrash
    @blasttrash 6 ปีที่แล้ว +29

    Is this Harsha? May his soul rest in peace. :'(

  • @anolhshete
    @anolhshete 8 ปีที่แล้ว +1

    In the last solution the time complexity will be O(max(m,n)) ? Is it correct or O(m+n) is correct , I know we can remove the constant factor but which is logically correct.

    • @sidddcloud
      @sidddcloud 5 ปีที่แล้ว +2

      I think o(m+n) means whichever is greater. So they are basically same.

  • @thinhnguyenvan7003
    @thinhnguyenvan7003 3 ปีที่แล้ว

    I think in method 2, we use dictionary will give you linear time complex

  • @ravindercool005
    @ravindercool005 9 ปีที่แล้ว

    Very nice explanation ..Thnks alot sir .

  • @liwaiyip1769
    @liwaiyip1769 4 ปีที่แล้ว

    Amazing job! Thank you very much.

  • @kaustavbora2024
    @kaustavbora2024 4 ปีที่แล้ว

    Swap function is wrong
    Please update it
    Right One:-
    if(m > n)
    {
    SinglyLinkedListNode* temp;
    temp=head1;
    head1=head2;
    head2=temp;
    d=m-n;
    }

  • @ShekharKumar8034
    @ShekharKumar8034 10 ปีที่แล้ว

    Nice and simple explanation sir.. Thanks :)

  • @zy5522
    @zy5522 7 หลายเดือนก่อน

    Thanks😊

  • @jsrgbh0
    @jsrgbh0 8 ปีที่แล้ว

    Have seen few of your videos and liked them all.
    Most of your solutions are focused on C and C++, Possible for you to provide the Java code snippet as well?

  • @seemcat
    @seemcat 5 ปีที่แล้ว

    Great explanation. Thanks!

  • @magicsmoke0
    @magicsmoke0 9 ปีที่แล้ว

    How would you do the Set approach in C# where references to managed objects don't have addresses (you would have to do some trickery with the GCHandle to get it)?

  • @AddieInGermany
    @AddieInGermany 7 ปีที่แล้ว

    Nicely explained. Thanks

  • @nikhilnikhil3517
    @nikhilnikhil3517 3 ปีที่แล้ว

    Shouldn't the time complexity be O(max(m,n)) as we are basically traversing the longer list fully in worst case i.e. when no merge point is found.

  • @vijayendrasdm
    @vijayendrasdm 10 ปีที่แล้ว

    For the approach 2, why did not you use unordered_map ?
    unordered_map has insertion/retrieve complexity of O(1).
    By using this we could have reduced TC to O(n) .
    Correct me if I am wrong

    • @lorenzocastillo6850
      @lorenzocastillo6850 10 ปีที่แล้ว

      O(M+N) time, but obv you need space for the hash table.

  • @udaykiran-yi2dv
    @udaykiran-yi2dv 8 ปีที่แล้ว

    excellent Explanation

  • @abhishekkaukuntla6762
    @abhishekkaukuntla6762 8 ปีที่แล้ว +1

    What if the first node itself is the merge point? What's the rule to evaluate d then, considering length(A) < length(B)?
    If we skip d places, we would miss the merge point.

    • @Gre05
      @Gre05 8 ปีที่แล้ว

      +Nikolay Jivkov I didn't understand it, because if the first node is merge with first node of B, we can skip it.

    • @mithessen
      @mithessen 8 ปีที่แล้ว

      It seems that there is an implicit assumption that after the merge point the lists remain same throughout. If there were multiple merge points to be considered such as in lists which converged, diverged and then re-converged, then it would need additional checks and balances.

    • @preetsinghkhalsa1204
      @preetsinghkhalsa1204 6 ปีที่แล้ว +1

      A list cannot diverge since there's only one parameter for next node in the structure.

    • @yasser_hussain
      @yasser_hussain 6 ปีที่แล้ว

      That can only happen if both lists are identical. Remember linked lists can't diverge.

  • @aayush5474
    @aayush5474 4 ปีที่แล้ว

    waht will main look like?

  • @siddharth__pandey
    @siddharth__pandey 6 ปีที่แล้ว

    your website is showing a bad gateway error.. please fix

  • @curiosity9861
    @curiosity9861 4 ปีที่แล้ว

    At 1:29 we have different addresses of value 7 in linked list 1 and linked list 2 so how we can check for the equality of it?

    • @prateektewary7526
      @prateektewary7526 3 ปีที่แล้ว

      Here we are not searching for similar values of nodes rather a "merge point". The two linked list at 1:29 have same values of two nodes but no merge point.

  • @KhaledChikhComptable
    @KhaledChikhComptable 10 ปีที่แล้ว

    Good tutorial

  • @NiranjhanaNarayanan
    @NiranjhanaNarayanan 8 ปีที่แล้ว

    Hey when we are passing the head node pointer (for the length function), isn't that by reference? So when we traverse it, doesn't the value get modified and the value of the start of the linked list get lost?

  • @hassnainali6872
    @hassnainali6872 5 ปีที่แล้ว

    Can't we recursively go to the end of each list, and on each return, compare the pointers with each other up till the last point where they are similar ?

    • @redraushan
      @redraushan 4 ปีที่แล้ว

      That would still be brute-force way way of doing it, basically you are asking why to do merge sort if be can do bubble sort, I think that's the difference.

  • @CSshreyas
    @CSshreyas 8 ปีที่แล้ว

    what about going to the end of the list and traverse back until there the nodes have same value?

    • @codingcart
      @codingcart 4 ปีที่แล้ว

      th-cam.com/video/WcOdcUHOA1M/w-d-xo.html

  • @mayanksrivastava4452
    @mayanksrivastava4452 7 ปีที่แล้ว

    amazing video

  • @AbhayKumar-uw8or
    @AbhayKumar-uw8or 4 ปีที่แล้ว

    i think its wrong as what if the d more nodes itself contain the merge point that you have just skipped to make the length same

  • @sureshdharavath1191
    @sureshdharavath1191 10 ปีที่แล้ว +1

    In brute force without finding the length lists can't it possible ?
    I guess by creating two temporary nodes which points to the head of the given nodes.

    • @mycodeschool
      @mycodeschool  10 ปีที่แล้ว

      Suresh D.Naik Can you detail your approach?

    • @saurabhchauhan1567
      @saurabhchauhan1567 8 ปีที่แล้ว +3

      +Suresh Dharavath it is possible but i will not change the complexity of the solution

    • @sartmeh1
      @sartmeh1 8 ปีที่แล้ว +1

      He means by using two while loops with each while loop designated with either list to check for NULL in link lists.This can save up a little bit of memory but still the complexity shall remain same i.e. O(mn).

  • @mavrck159
    @mavrck159 6 ปีที่แล้ว

    SnackDown is here! Only one global champion will take the title home. Let the Code War begin! Registrations are now OPEN for SnackDown 2019!
    www.codechef.com/snackdown?ref=sssshhhh

  • @mybozlo
    @mybozlo 9 ปีที่แล้ว

    In #3 case, what if the merge point in d area ?

    • @SourabhVartak1985
      @SourabhVartak1985 9 ปีที่แล้ว +1

      +IL JUN LEE
      The d area is where one linked list has more elements than the other linked list.
      So, the merge point can not occur in the d area because only one list is active there.

  • @shruthib6635
    @shruthib6635 6 ปีที่แล้ว

    what if 2 lists diverge after some point.... How are we handling this case

    • @shankarn4021
      @shankarn4021 6 ปีที่แล้ว

      The linked list(mentioned in the video) has only one next* pointer, so it's impossible to have the list point to 2 different nodes.

  • @RajbirYadav
    @RajbirYadav 9 ปีที่แล้ว

    awesome!

  • @parmeetsingh7410
    @parmeetsingh7410 6 ปีที่แล้ว

    can we compare node's data instead of node's address???

    • @utsavdahiya3729
      @utsavdahiya3729 6 ปีที่แล้ว +2

      No, data values are not unique to each node

    • @parmeetsingh7410
      @parmeetsingh7410 6 ปีที่แล้ว

      utsav dahiya can you please explain through an example,I am still confused?

  • @Niteshkumar-zd3kr
    @Niteshkumar-zd3kr 5 ปีที่แล้ว

    Are you comparing addresses or the values?

    • @subham-raj
      @subham-raj 5 ปีที่แล้ว

      The node as a whole.

    • @codingcart
      @codingcart 4 ปีที่แล้ว

      th-cam.com/video/WcOdcUHOA1M/w-d-xo.html

  • @anupamshankardey8737
    @anupamshankardey8737 7 ปีที่แล้ว

    which IDE have you used during this lesson?

  • @FrozenByTheSun
    @FrozenByTheSun 6 ปีที่แล้ว +2

    Is this Harsha?

    • @blasttrash
      @blasttrash 6 ปีที่แล้ว +1

      I had the same question. If it was, I just feel so sad. May his soul rest in peace.

    • @urcristiano77882
      @urcristiano77882 5 ปีที่แล้ว

      who is harsha ?

    • @blasttrash
      @blasttrash 5 ปีที่แล้ว +1

      Harsha is one of the two guys who started this channel. Apparently Harsha met with accident or something.

    • @urcristiano77882
      @urcristiano77882 5 ปีที่แล้ว

      okayy thanks

  • @suguruchhaya3194
    @suguruchhaya3194 3 ปีที่แล้ว

    Who else is comming from the HackerRank question? Just want to let you know that you have to return the '.data' of the node instead of the node itself in the question.

  • @kunalsoni7681
    @kunalsoni7681 4 ปีที่แล้ว +1

    😍😍😍😊😊😊😊

    • @lyfokzz3848
      @lyfokzz3848 4 ปีที่แล้ว

      unfortunatly he passed away bro...

    • @kunalsoni7681
      @kunalsoni7681 4 ปีที่แล้ว

      @@lyfokzz3848 what it mean bro

    • @lyfokzz3848
      @lyfokzz3848 4 ปีที่แล้ว

      The instructors name was Late Harsha suryanarayan. He was the best coder of all time.You can google it for more information.

    • @kunalsoni7681
      @kunalsoni7681 4 ปีที่แล้ว

      @@lyfokzz3848 thanks bro😉

    • @lyfokzz3848
      @lyfokzz3848 4 ปีที่แล้ว

      @@kunalsoni7681 welcm dude. And happy coding.

  • @arpitsatnalika
    @arpitsatnalika 3 ปีที่แล้ว

    This code will fail for linked list like this [4,1,8,4,5]
    and [5,6,1,8,4,5]