Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)

Sdílet
Vložit
  • čas přidán 23. 01. 2019
  • Free 5-Day Mini-Course: backtobackswe.com
    Try Our Full Platform: backtobackswe.com/pricing
    📹 Intuitive Video Explanations
    🏃 Run Code As You Learn
    💾 Save Progress
    ❓New Unseen Questions
    🔎 Get All Solutions
    Question: Given two lists that are sorted, merge them into a single sorted sequence as efficiently as possible.
    The key with linked list problems is pointers. Most of what we will do will be O(n) time and O(1) space.
    It is all about hardwiring things together and moving pointers around, have a strong understanding of techniques to advance, stash, and move references around.
    Approach 1 (Brute Force)
    Append the lists together and then sort the lists.
    The best we can do with this is O( n * log(n) ) because we will only know the total ordering property of the lists which lets us use (Mergesort or Quicksort, etc.)
    Approach 2 (Use Pointers And Rewire Lists)
    Huge tip. When building a new list while doing linked list problems dummy heads are your best friend. They prevent you from having to do null checks on a list and you can immediately append to the .next value through a pointer to it with no fear of a null pointer exception.
    We just keep:
    1.) a pointer to the last item in the new list we are building
    2.) a pointer into the first list
    3.) a pointer into the second list
    We then do pair comparisons and advance accordingly.
    Complexities
    Time: O( m + n )
    Let n be the length of list 1.
    Let m be the length of list 2.
    This is the worst case. We will be traversing the whole length of the lists in the case where they are nearly similar in length and value comparison results (aka we don't exhaust a list early before another).
    Best case is O( min( m, n ) ) because we will only traverse as far as we need to exhaust the shorter of the lists, then we just append the rest of the other onto the result since it will all be greater than the exhausted list by default.
    Space: O( 1 )
    We are only working with pointers. We are using the existing nodes given to us.
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    HackerRank: / @hackerrankofficial
    Tuschar Roy: / tusharroy2525
    GeeksForGeeks: / @geeksforgeeksvideos
    Jarvis Johnson: / vsympathyv
    Success In Tech: / @successintech
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    This question is number 8.1 in "Elements of Programming Interviews" by Adnan Aziz, Tsung-Hsien Lee, and Amit Prakash.
  • Věda a technologie

Komentáře • 134

  • @BackToBackSWE
    @BackToBackSWE  Před 5 lety +10

    Table of Contents:
    The Problem Introduction 0:00 - 1:06
    Merging The Lists: Walkthrough 1:06 - 5:51
    We Have Exhausted The 2nd List 5:51 - 6:48
    The Merging Is Finished 6:48 - 7:39
    Time Complexity 7:39 - 8:25
    Space Complexity 8:25 - 8:51
    Wrap Up 8:51 - 9:16
    The code for this problem is in the description. For both the iterative and recursive approaches. Fully commented for teaching purposes.

    • @cguy3633
      @cguy3633 Před 3 lety +6

      I do not see the code

  • @abebe7017
    @abebe7017 Před 4 lety +51

    Thank you, dude! I was asked this question in my interview with Microsoft and I killed with no mercy!

  • @sheilferzepeda1124
    @sheilferzepeda1124 Před 5 lety +36

    You're an excellent educator and will be one of the reasons I find a good job. Thank you.

  • @SamWhitlock
    @SamWhitlock Před 5 lety +10

    Oh man I never realized the dummy technique before. This makes life so much easier than a nullptr and a conditional one hits every time!

  • @ADash
    @ADash Před 3 lety +2

    This was a great explanation! Really helped me understand the concepts, thanks!

  • @The1131
    @The1131 Před 2 lety +4

    Thank you for your videos and your enthusiasm is definitely infectious! I have never been so eager to solve LinkedList problems 😂

  • @Alireza13488
    @Alireza13488 Před 2 lety +1

    this was by far the clearest explaination I have seen on this problem. Thank you

  • @seemcat
    @seemcat Před 5 lety +4

    You are SO good at explaining these algorithms! Thank you for sharing.

  • @robokarizma0308
    @robokarizma0308 Před 5 lety +3

    You are great !
    Had trouble understanding mergesort stuff before this.
    You made everything crystal clear

  • @Milchmann2
    @Milchmann2 Před 5 lety +4

    All of your videos are a joy to watch and helpful. Really insightful and well explained. You are awesome. Best of luck with your channel, I think you will do great.
    Thanks a lot!

    • @BackToBackSWE
      @BackToBackSWE  Před 5 lety

      Thank you. Very long way to go...I can't be content.

  • @aaditshah5825
    @aaditshah5825 Před 2 lety

    Awesome content. Keep up the good work my man!

  • @roberttaylor8391
    @roberttaylor8391 Před 4 lety +1

    These videos are so good! Thank you again for providing these.

  • @snake1625b
    @snake1625b Před 5 lety +2

    10/10 whiteboard explanations are the best and most intuitive way to learn!

  • @allmight31
    @allmight31 Před 4 lety +1

    I'm learning so much from your videos. Thank you and keep it up!

  • @mayawhocodes3092
    @mayawhocodes3092 Před 2 lety

    You bodied this explanation. Thank yoooou!

  • @afridimajeed5897
    @afridimajeed5897 Před 3 lety

    I FINALLY GOT IT! Thank you!!

  • @GG-sw9vm
    @GG-sw9vm Před rokem

    After being in the industry for 10 years and barely using any data structure, it feels good to learn about DS again.

  • @bhargavvaidya4032
    @bhargavvaidya4032 Před 3 lety

    Super useful video for my computer science test - just subscribed

  • @barbosikd
    @barbosikd Před 4 lety +1

    This is awesome. Thank you, my man

  • @satyamrajsingh7378
    @satyamrajsingh7378 Před 5 lety +1

    Sir You are the best ever tutor on CZcams in the sense of interest that you create in the mind of the student.. Exception to the tutors who make coding boring

  • @pranjalchandel3732
    @pranjalchandel3732 Před 5 lety +3

    Man please keep uploading regularly don't take a break...because bro we want to study from you...on a regular basis...

    • @BackToBackSWE
      @BackToBackSWE  Před 5 lety

      hahahahahaha, yeah I've been busy with work at Twitter - I get home at like 6 normally and then I answer email and then it is 7 and then I'm tired so I read and then it is 8....so yeah, I'm here....I'll be in school soon so I'll make videos part-time again & make a structured course

    • @pranjalchandel3732
      @pranjalchandel3732 Před 5 lety +1

      @@BackToBackSWE yo our saviour is back...bro really please make a video on how to flatten a linked list...

    • @BackToBackSWE
      @BackToBackSWE  Před 5 lety

      @@pranjalchandel3732 hahaha ok

  • @prithazz
    @prithazz Před 4 lety +2

    So clear how the cur is used as a navigator and thats why we return dummy.next! love it things are clicking :)

  • @switchu2968
    @switchu2968 Před 3 lety

    Best explanation I've ever seen.

  • @xarakus
    @xarakus Před 3 lety

    well explained. thanks

  • @nicholasberejan4270
    @nicholasberejan4270 Před 9 dny

    Immensely helpful. Thank you so much.

  • @dylangarvey4128
    @dylangarvey4128 Před rokem

    Great videos. The shmedium t shirts are an added benefit

  • @parteeksachdeva3039
    @parteeksachdeva3039 Před 4 lety +1

    This makes it too much easy to understand, thakyou and keep up

  • @mikedelta658
    @mikedelta658 Před 5 měsíci

    Thank you!

  • @priyaranjansingh6814
    @priyaranjansingh6814 Před 5 lety +1

    Thanks man keep up the good work :)

  • @yicai7
    @yicai7 Před 3 lety

    What a genius!!

  • @dariamartin2675
    @dariamartin2675 Před 5 lety +1

    This was so helpful!

  • @dorislewis6604
    @dorislewis6604 Před rokem

    very clear! useful for me to understand the concept!!!!

    • @BackToBackSWE
      @BackToBackSWE  Před rokem

      Glad it was helpful! 😄 Also check out our FREE DSA Interview Prep Mini-Course - backtobackswe.com/ 🎉

  • @Drewster301
    @Drewster301 Před rokem

    yo this explanation was so good. thanks man!

    • @BackToBackSWE
      @BackToBackSWE  Před rokem

      Glad it helped 😄 Also check out our Free 5 Day DSA Interview Prep Mini-Course - backtobackswe.com/ 🎉

  • @akankshasharma148
    @akankshasharma148 Před 3 lety

    Man you are a awesome teacher🙌🙌

  • @MohitGupta-jm7if
    @MohitGupta-jm7if Před 5 lety +1

    Man you are truly awesome

  • @yicai7
    @yicai7 Před 4 lety +1

    Cheers! :)
    Share your wonderful video in the leetcode discuss again!

  • @rosegoldfarb2815
    @rosegoldfarb2815 Před 3 lety +3

    Thanks for the video! Just one question since I've worked with pointers in C and I'm just curious how the "pointers" in python work. Is setting head = cur similar to making head point to cur? Thanks!

  • @reinasama904
    @reinasama904 Před rokem

    Amazing video, thank you so much.

    • @BackToBackSWE
      @BackToBackSWE  Před rokem +1

      Thank you 😄 We'd love for you to check out our Free 5 Day DSA Interview Prep Mini-Course - backtobackswe.com/ 🎉

  • @chrisogonas
    @chrisogonas Před 2 lety

    Superb!

  • @positiveoptimist5060
    @positiveoptimist5060 Před rokem

    I've watched a bunch of videos on this LC question and they just write code without any depth. This brother is a great instructor (I can tell, I was a teacher). Keep up the great work yo!

    • @BackToBackSWE
      @BackToBackSWE  Před rokem

      thank you so much! There are other questions at - backtobackswe.com/ - Would love some feedback

    • @positiveoptimist5060
      @positiveoptimist5060 Před rokem

      @@BackToBackSWE You're welcome! Funny you mentioned that, I purchased a lifetime subscription on your platform.
      My goal is to join a big tech company in the next 6-12 months. I will comment here when I make that happen.

    • @BackToBackSWE
      @BackToBackSWE  Před rokem

      Amazing. All the best, just waiting for your comment now 💯🎉 keep us posted

  • @memonauta
    @memonauta Před 3 lety +1

    Great explanation man.

  • @bossmusa9075
    @bossmusa9075 Před 11 měsíci

    thank you

  • @Alireza13488
    @Alireza13488 Před 3 lety

    bruh the way you music Interrupted you in the end killed me xD

  • @nikolalakic8863
    @nikolalakic8863 Před 5 lety +1

    Dude you are awesome

  • @riyashetye6657
    @riyashetye6657 Před 2 lety +1

    Thank you so much

    • @BackToBackSWE
      @BackToBackSWE  Před 2 lety

      Awesome! Do try our free mini course backtobackswe.com/

  • @pritomdasradheshyam2154
    @pritomdasradheshyam2154 Před 4 lety +1

    Very good explanation :)

  • @testingDhippiuh
    @testingDhippiuh Před 4 lety +1

    Thanks for sharing

  • @anirudhr4710
    @anirudhr4710 Před rokem

    amazing sir

  • @pratyakshyt
    @pratyakshyt Před 3 lety

    Thanks

  • @airysm
    @airysm Před 5 lety +2

    Can’t believe you’re only a sophomore man! I’ve pretty much watched every video in this series for the most part and I got 2 questions (not related to the video lol):
    1) What do you think would be your dream company you would want to go to as a new grad?
    2) how did you get so good at Leetcode lol

    • @BackToBackSWE
      @BackToBackSWE  Před 5 lety +11

      1.) Not sure. I'm less concerned about my future and MUCH more concerned about the future of Back To Back SWE. I want this to be the largest channel/resource for this in the world and...that is not a small task to undertake for anyone. So yes...that keeps me up at night...basically every night.
      2.) I explain how in the video "How To Get A Job At Google", the main video on this channel. A lot of pain and suffering alone behind a computer screen. Doing problems, reading EPI (Elements of Programming Interviews) several times.
      I mean...I don't get paid for this (ads make nothing, trust me...at least right now), each video takes at least 4 hours to do, the problems are dry...what else can keep a human going doing this if it is not beyond the traditional reward system? (money, adoration, etc.)
      I see this channel's completion as a purpose that must happen. I can rest after but as long as there are other "past me's" in the world without a guide...I can't feel ok with myself.

    • @airysm
      @airysm Před 5 lety +1

      Back To Back SWE wow man thank you for making that dedication. I definitely see this channel as becoming the main resource channel for interviewing. You have a way of explaining that’s really easy to follow compared to other channels. Keep up the great work!

    • @BackToBackSWE
      @BackToBackSWE  Před 5 lety

      @@airysm 👍

  • @allen6112
    @allen6112 Před 5 lety +2

    Great explanation. Can you do a video on "Flatten Nested List Iterator"?

  • @hikemalliday6007
    @hikemalliday6007 Před rokem

    Dude you just explained that shit so well

    • @BackToBackSWE
      @BackToBackSWE  Před rokem

      Haha Really glad to help 🎉 Do you know about our 5-Day Free DSA Mini Course? Check it out here - backtobackswe.com/

  • @zhaowencheng8690
    @zhaowencheng8690 Před 3 lety +2

    Hi sir, could you please explain why dummy_head works? I mean, the curr pointer moves one step each, and dummy_head = curr, so why dummy_head didn't move at all? Thank you so much, have a great weekend!

  • @bixbyknolls
    @bixbyknolls Před 5 lety +1

    Although I just finished that problem in very similar way I find this video super helpful. Like you mentioned, Linked List is confusing but you make it very clear. Keep up with the amazing work!

    • @BackToBackSWE
      @BackToBackSWE  Před 5 lety +1

      Tricky until you do a lot of them, yeah. Thank you.

  • @ajaymahar5538
    @ajaymahar5538 Před 3 lety +2

    Nice! one. just a small correction on time complex : I think time taken by the function would be O(n) where n is the length of the smallest list.
    WHY?
    here is the thing...
    we are traversing the the list until one list get exhausted. once we know there is no list to compare we simply pointing to the other list, and we know other list would be the sorted, and that is constant operation.
    Open for discussion.... :)

    • @vrnkna
      @vrnkna Před 7 měsíci

      For big O you consider the worst case, which means you exhausted both linked lists. Therefore, it would be O(m + n).

  • @jellywu4095
    @jellywu4095 Před 5 lety +1

    Can you please explain where in the code the pointer for dummy head is set to the first element of the sorted list? Everything else except for that makes sense to me. Thanks!

  • @jxujessica
    @jxujessica Před 3 lety

    so are we breaking the original two lists or we are building a brand new list?

  • @seal0118
    @seal0118 Před 4 lety +1

    7:51 the struggle lol
    but its true, whenever there is a number variable i always use n first because "numbers" duh ..

  • @canernm
    @canernm Před 3 lety +1

    Thanks, got a quick question if you could answer. If we have two sorted arrays of the same length n, then in order to merge them like you taught us we will have to make 2n-1 comparisons right? That means that the total steps needed are 2n-1 and not 2n. Is this correct? Thanks in advance.

    • @BackToBackSWE
      @BackToBackSWE  Před 3 lety +1

      Yeah I think? Fuzzy memory

    • @canernm
      @canernm Před 3 lety

      @@BackToBackSWE Yeah you answered this question in detail during the mergesort video that I watched afterwards. Thank you !

  • @duylamnguyen6812
    @duylamnguyen6812 Před 2 lety

    I am new to programming. Could someone please tell me why we need to do this practice? In python, we have functions to merge and sort lists.

  • @yichuanfeng4491
    @yichuanfeng4491 Před 4 lety +3

    I have a question: how does dummy change?
    I get it that 'cur' and 'dummy' are pointing to the same object, but not clear about how they are linked exactly.
    Or maybe asking in this way:
    What does 'cur=cur.next' and 'cur.next=l1' do to dummy respectively?
    Thank you!

    • @BackToBackSWE
      @BackToBackSWE  Před 4 lety +1

      curr advances as we merge the lists. The dummy heads always stay stationary. These are pointers to memory locations.
      curr.next points to a new memory location. curr points to a new memory location (where curr.next sits). the dummy head never changes what it references to.

    • @yichuanfeng4491
      @yichuanfeng4491 Před 4 lety

      Thank you for the explanation. But still a little puzzled. How does dummy change?

    • @yichuanfeng4491
      @yichuanfeng4491 Před 4 lety

      I understand that dummy stays stationary but how come it is like expanding?

    • @praisong7475
      @praisong7475 Před 4 lety

      @@yichuanfeng4491 That's why we return dummy.next which gives you the connections curr has made throughout the two linked lists, starting from the dummy head.

  • @Hizzle182
    @Hizzle182 Před 4 lety +1

    struggling with big O stuff. Don't you take up n + m space if you're given two arrays as input and you initialize a couple linked lists from the arrays?

    • @BackToBackSWE
      @BackToBackSWE  Před 4 lety

      Yes, but here we are given linked lists and we just rewire them.

    • @Hizzle182
      @Hizzle182 Před 4 lety +1

      @@BackToBackSWE OK, thanks. Love what you're doing. Keep it up. It's huge.

    • @BackToBackSWE
      @BackToBackSWE  Před 4 lety

      @@Hizzle182 ok haha

  • @izanagi6469
    @izanagi6469 Před 4 lety +1

    Ilyyyy

  • @ramr3
    @ramr3 Před 4 lety +1

    In
    if(l1.val < l2.val){
    dummy.next = l1;
    l1 = l1.next;
    }
    why isn't it that the entire list is apended to cur.?
    But when you finish the loop because one list is null and you do
    if(l1 == null){
    dummy.next = l2;
    }
    then all of a sudden the entire l2 list appends itself to cur. I'm confused in leetCode if ListNode is a pointer or if it represents the entire list?

    • @BackToBackSWE
      @BackToBackSWE  Před 4 lety

      It is a linked list, the nodes are linked like a chain. Think on it

  • @evangelinem.8989
    @evangelinem.8989 Před 10 měsíci

    So, it's not like we remove anything from the lists to put them inside a dummy list. We simply change where each node is pointing towards to end up with one dummy list and no more list1 and list2?

    • @evangelinem.8989
      @evangelinem.8989 Před 10 měsíci

      Plus, everytime we have to do the manipulation of pointing cur, THEN moving it?

  • @gurmukhsinghnirman4935
    @gurmukhsinghnirman4935 Před 4 lety +1

    Hey, where is the code i'm not able to find it in desc?

    • @BackToBackSWE
      @BackToBackSWE  Před 4 lety

      The repository is deprecated - we only maintain backtobackswe.com now.

  • @nikhildikshit511
    @nikhildikshit511 Před 5 lety +1

    From your code -
    current.next = p1 != null ? p1 : p2;
    This is just an OR operation, right?

    • @BackToBackSWE
      @BackToBackSWE  Před 5 lety

      It is a ternary operator: tutorials.jenkov.com/java/ternary-operator.html

  • @Richard-yz2gy
    @Richard-yz2gy Před 10 měsíci

    Im confused you said you that you cant build a list off cur if cur is none, but in other videos I have seen lists built off cur when cur is none :)

  • @davidbarnwell6180
    @davidbarnwell6180 Před 7 měsíci

    What if you are merging two lists in a merge sort and the lists have an element in common?

    • @ythalorossy
      @ythalorossy Před 5 měsíci +1

      When comparing if the value from L1 is lower than L2 it will return false, because the value are equals. So, you move to the else statement that will get the value from the L2.

  • @ottyudo7208
    @ottyudo7208 Před 4 lety +1

    Please, can someone paste the code as a reply here?

    • @BackToBackSWE
      @BackToBackSWE  Před 4 lety

      The repository is deprecated - we only maintain backtobackswe.com now.

  • @mardokaymosazghi1296
    @mardokaymosazghi1296 Před 5 lety +2

    First 😁

  • @carloscab3854
    @carloscab3854 Před 3 lety +1

    you need more interaction with the whiteboard, the whiteboard is an extension in real time of your verbal explanation, not to happen at t-1 time

  • @lilyh4573
    @lilyh4573 Před 2 lety

    Is there a written solution to this?

    • @BackToBackSWE
      @BackToBackSWE  Před rokem +1

      You can check out the code repository on backtobackswe.com/