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