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

Back To Back SWE · Beginner ·⚡ Algorithms & Data Structures ·7y ago

Key Takeaways

The video demonstrates a fundamental merge sort subroutine to merge two sorted lists into a single sorted list, with a time complexity of O(M+N) and constant space usage by adjusting pointers and comparing elements.

Full Transcript

all right so today we are going to look at how we sort or merge two sorted lists now Alyss is an abstraction I can have a linked list I could have an array so the question on lis code is with linked lists or walkthrough will be with a linked list so I can show you how it's done and how we can like avoid some work at the end you'll see what I mean in like a little case where we exhaust one list but so the question is given two sorted lists this is very similar to my video talking about merging K sorted lists this is actually a smaller video in scope because this is the fundamental that I built off in that video merging two sorted lists this is very important for algorithms like merge sort I have a video on merge sort for algorithms like merge sort we need to know how to merge two sorted lists because what we do is we drill down to base cases and those base cases push us back upwards and we have sorted lists as we go back upwards and medium merge those after doing the split steps for this problem two sorted lists we have a sorted list how do we do this let's look at how we do this so we're gonna do this with a linked list so the thing is length las' problems are pretty tricky when I first started learning them I was horrible at like pointer manipulation and moving those pointers around to solve problems linked those problems can become very easy with practice and just like knowing the methods that we do to work with these nodes so what we're gonna do for this problem is we're going to put a pointer at the beginning of each of these lists and we're going to use a dummy head to builds this new list so this is what the setup looks like all right so we have pointers on each of our first nodes we have a dummy head I really like using dummy head nodes for limitless problems why because we do not need to worry about having an empty state on the dummy head when we're building our new list if I put a pointer cur on this head which is what we're going to do actually let me rename things so it's a little more clear so what I'm going to do is I'm going to build my list off of curve if I didn't have a dummy head what if cur is know what occur has nothing I can't just say cur Tom next because what if the actual her is not a dummy head node gets rid of this problem by when we points occur I know it's gonna have a value it's just going to be my dummy head I keep saying dummy head this is kind of annoying so I point list 1 points are here L 2 points are there we are going to advance those pointers as we eat up the parts of the list and we choose items so we perform our first comparison we want the lesser item the lesser item gets the placement if they're equal we can take it from both list one or list two negative one versus one the smaller item is going to be negative one negative one gets the placement so this is what happens so what just happened I appended the negative one node to the dummy head so now this is the first node in our list and it's the last node in our list and what I did was I moved her to this node so cur is always going to be pointing at the tail of the list we are building the tail of the sorted list we are building and I advanced L 2 and now L 2 points here and now we can continue our comparisons between l1 and l2 and advance and just stay with me it becomes very straightforward the thing about these length list problems is they're often done in M plus n time or linear time and we use constant space because it's just about rewiring it's literally like reelect wrists we're just rewiring stuff so what we do is 1 versus 2 one gets the placement because it is less so turn X we point it to list 1 and we advance list 1 and of course we advance occur to the tail of the sorted list cur always points to the tail of the sorted list and so as you can see we rewired the node kurwa sitting at 2 now points to this node and now cur hops itself to what it just pointed itself to because current needs to stay at the end of the sorted list so list 1 is sitting here list 2 is sitting here those are pointers they're pointing into the lists so 2 versus 3 2 gets the placement let's do our rewiring we advance list 2 because we just add up to one of its nodes we point this node that cur is pointing to to this node I Bakr hops on to the node is pointed to and now Kearney's who stay at details and list always that's what happens and so now do you notice how as we're going through this we're slowly building up a sorted list we start at negative one we go to one we go to two so you see it slowly we're eating up these lists through these comparisons and we're building a sorted list so now what we do is compare list one and list two again cur is sitting at the tail of the sorted list this is the sorted list this is the stuff we still are working on so now three and three hoomans so we can take it from either the list let's just take it from the list one so what we do is list one hops here we rewire the node that Curtis sitting on two points to the node that just one and now kurz got a point to the tail which is this node that is about 2.2 and again Curt always sits at the tail of the sorted list do you see how we're building a sorted list and now we continue our comparisons unprocessed territory processed territory unprocessed so now comparison three gets the placement the reverse is five three is the winner so now curve points over here this arrow gets erased curve points over here and then cur hops onto what I just pointed to and L to needs to advance because we just ate one of its nose and so now what we do is we look at l1 and l2 who is the winner the winner is altitude how to gets the placement we point cur to where l2 was and we move cur to the tail of the list for building which is the note that it is about 2.2 all right so now you see we're slowly building a sorted list and notice wait I've exhausted l2 so if I've exhausted l2 what conclusion can I make I can make the conclusion that everything from l1 and beyond is going to be greater than the last element in this list it's going to be greater than or equal to the last element in this list so I could still have a four there and I'd still tack this on so what we do is this is a linked list so all we need to do is I arrange this pointer I point to l1 I points to where l1 is pointing because we made the conclusion all these nodes must be greater and as you can see they are going to be greater than the element which is for we can make that 504 it still be greater than or equal to it so what I do is I point this note to l1 and then I am finished because I have exhausted the second list and I know that the first list is all going to be in the right place and so this is how our algorithm works and this is our final linked list so let's write it out so at the end of our function all we do is hey we have a reference to the dummy head point the dummy hat next return the value of dummy head next return the pointer to this note when we have the pointer to this node then bang we have our whole list negative 1 1 2 3 3 4 5 10 15 and this is how you merge a sorted list so this is just how we would do it with an array although with linked list is kind of easier because I can just do that pointer I could just adjust that pointer and then bang I have the first list in place first list is finished and we know it's going to be greater than this last item that is how you merge two sorted lists so now let's look at time complexity we always declare our variables when we're doing Big O so M is the length of the first list and is the length of the second list you can swap those I don't know why I put it in this order I shouldn't mean anything Swan anyway but M comes before and in alphabetical order but we use n more often so I would assume that guess precedence so the time complexity is going to be Big O of M plus and at worst we traverse the length of both of those lists if they're very similar we're going to have to do a lot of comparisons and then we'll go towards detail if they're very different if I have a list of 1 2 & 3 and then the other list is all values greater than 10 then I'm going to terminates very quickly and just do the rewiring and then jump out of there because I'm finished we're going to be using constant space we're going to be using constant space because all we're doing is shifting of pointers jumping around doing our little rewiring and then getting out of there we're not creating a whole new array we're not create who knows we're not creating an array we're not creating anything that will scale as our input gets arbitrarily large which is what's big o is about what these complexities and asymptotic analysis is about if you like this video if this was a clear explanation hit the like button subscribe I know that this video was kind of easy but the thing is we'll have our fair share of hourly code horns and Li code mediums we'll get to those and do those but I want to set a fundamental basis and teach these because it is key to have these fundamentals for our sorting algorithms and apply to other questions like merge K sorted lists that's all for this video [Music]

Original Description

Free 5-Day Mini-Course: https://backtobackswe.com Try Our Full Platform: https://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 existin
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Back To Back SWE · Back To Back SWE · 36 of 60

1 4 Tips To Learn Java Programming As Fast As Possible As A Beginner
4 Tips To Learn Java Programming As Fast As Possible As A Beginner
Back To Back SWE
2 3 Mistakes Beginners Make When First Learning Java and Android Development
3 Mistakes Beginners Make When First Learning Java and Android Development
Back To Back SWE
3 How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding Interviews
Back To Back SWE
4 The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
Back To Back SWE
5 Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)
Back To Back SWE
6 The N Queens Problem using Backtracking/Recursion - Explained
The N Queens Problem using Backtracking/Recursion - Explained
Back To Back SWE
7 Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Compute All Mnemonics For A Phone Number (Recursion/Backtracking Problem)
Back To Back SWE
8 How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
How To Reverse A Singly Linked List | The Ultimate Explanation (Iteratively & Recursively)
Back To Back SWE
9 Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Depth First & Breadth First Graph Search - DFS & BFS Graph Searching Algorithms
Back To Back SWE
10 The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
Back To Back SWE
11 The Dutch National Flag Problem (The Quicksort "Band-Aid")
The Dutch National Flag Problem (The Quicksort "Band-Aid")
Back To Back SWE
12 Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Test If A Binary Tree Is Symmetric ("Symmetric Tree" on Leetcode)
Back To Back SWE
13 The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
The IP Address Decomposition Problem - Compute All Valid IP Addresses From Raw IP String
Back To Back SWE
14 How To Permute A String - Generate All Permutations Of A String
How To Permute A String - Generate All Permutations Of A String
Back To Back SWE
15 The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
The Balanced Parentheses Problem - Classic Stack Problem ("Valid Parentheses" on Leetcode)
Back To Back SWE
16 Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search -  First Occurrence Of Substring
Knuth–Morris–Pratt (KMP) Pattern Matching Substring Search - First Occurrence Of Substring
Back To Back SWE
17 Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode)
Back To Back SWE
18 Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Find The Longest Increasing Subsequence - Dynamic Programming Fundamentals
Back To Back SWE
19 Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Generate All Palindromic Decompositions Of A String ("Palindrome Partitioning" on Leetcode)
Back To Back SWE
20 Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Implement A Sudoku Solver - Sudoku Solving Backtracking Algorithm ("Sudoku Solver" on LeetCode)
Back To Back SWE
21 Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Merge K Sorted Arrays - Min Heap Algorithm ("Merge K Sorted Lists" on LeetCode)
Back To Back SWE
22 Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Partition To K Equal Sum Subsets From An Array of Integers - The Backtracking Approach
Back To Back SWE
23 Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Back To Back SWE
24 Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Total Ways To Decode A String - Recursive Dynamic Programming Approach ("Decode Ways" on LeetCode)
Back To Back SWE
25 The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
Back To Back SWE
26 Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode)
Back To Back SWE
27 Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Count Total Unique Binary Search Trees - The nth Catalan Number (Dynamic Programming)
Back To Back SWE
28 Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Generate All Strings With n Matched Parentheses - Backtracking ("Generate Parentheses" on LeetCode)
Back To Back SWE
29 Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Implement A Max Stack - A Stack With A .max() API (Similar To "Min Stack" on LeetCode)
Back To Back SWE
30 The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
The Recursive Staircase - Top Down & Bottom Up Dynamic Programming ("Climbing Stairs" on LeetCode)
Back To Back SWE
31 Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)
Back To Back SWE
32 Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Total Unique Ways To Make Change - Dynamic Programming ("Coin Change 2" on LeetCode)
Back To Back SWE
33 Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)
Back To Back SWE
34 Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)
Back To Back SWE
35 Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Increment An Integer Represented As An Array ("Plus One" on LeetCode)
Back To Back SWE
Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode)
Back To Back SWE
37 Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Clone An Undirected Graph - The Utility of Hashtable Mappings ("Clone Graph" on Leetcode)
Back To Back SWE
38 Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution
Back To Back SWE
39 Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Deeply Understanding Logarithms In Time Complexities & Their Role In Computer Science
Back To Back SWE
40 Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)
Back To Back SWE
41 Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Max Contiguous Subarray Sum - Cubic Time To Kadane's Algorithm ("Maximum Subarray" on LeetCode)
Back To Back SWE
42 Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.
Back To Back SWE
43 What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
What Is Asymptotic Analysis? And Why Does It Matter? A Deeper Understanding of Asymptotic Notation.
Back To Back SWE
44 An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
An In-Depth Algorithmic Analysis of Bubble Sort. Best Case, Average Case, & Worst Case.
Back To Back SWE
45 Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming)
Back To Back SWE
46 A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
A Detailed Algorithmic Analysis of Insertion Sort. Best Case & Worst Case.
Back To Back SWE
47 Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Binary Tree Level Order Traversal - Drawing The Parallel Between Trees & Graphs
Back To Back SWE
48 Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Implement A Queue Using Stacks - The Queue ADT ("Implement Queue Using Stacks" on LeetCode)
Back To Back SWE
49 All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
All Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A Hashtable
Back To Back SWE
50 Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
Back To Back SWE
51 Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Egg Dropping Problem: Dynamic Programming Fundamentals & Understanding Subproblem Decomposition
Back To Back SWE
52 Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Minimum Window Substring: Utilizing Two Pointers & Tracking Character Mappings With A Hashtable
Back To Back SWE
53 Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Reverse Polish Notation: Types of Mathematical Notations & Using A Stack To Solve RPN Expressions
Back To Back SWE
54 Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Asymptotic Notations 101: Big O, Big Omega, & Theta (Asymptotic Analysis Bootcamp)
Back To Back SWE
55 The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms
Back To Back SWE
56 Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Fast Multiplication: From Grade-School Multiplication To Karatsuba's Algorithm
Back To Back SWE
57 Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Search A 2D Sorted Matrix - Fundamentals of Search Space Reduction
Back To Back SWE
58 The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
The Quicksort Sorting Algorithm: Pick A Pivot, Partition, & Recurse
Back To Back SWE
59 Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Lowest Common Ancestor Between 2 Binary Tree Nodes (A Recursive Approach)
Back To Back SWE
60 Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Sort A K Sorted Array - Investigating Applications of Min/Max Heaps
Back To Back SWE

This video teaches how to merge two sorted lists into a single sorted list using a fundamental merge sort subroutine, with a focus on time complexity and constant space usage. The subroutine uses two pointers to compare elements and rewire nodes to build a sorted list.

Key Takeaways
  1. Declare variables M and N for the lengths of the two lists
  2. Compare elements from both lists and place them in the correct order
  3. Rewire the nodes to build a sorted list
  4. Adjust the pointers to point to the correct nodes
  5. Return the pointer to the head of the merged list
  6. Adjust pointers to merge two sorted lists
  7. Compare elements to determine the correct order
💡 The merge sort subroutine can be implemented with a time complexity of O(M+N) and constant space usage by only shifting pointers and not creating a new array.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →