0021. Merge Two Sorted Lists
Problem Statement
You are given the heads of two sorted linked lists, list1
and list2
. The task is to merge these two lists into one sorted list. The merged list should be created by splicing together the nodes of the first two lists. Finally, return the head of the merged linked list.
Constraints
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
.- Both
list1
andlist2
are sorted in non-decreasing order.
Example Use Cases
Example 1
- Input:
list1 = [1, 2, 4]
,list2 = [1, 3, 4]
- Output:
[1, 1, 2, 3, 4, 4]
Example 2
- Input:
list1 = []
,list2 = []
- Output:
[]
Example 3
- Input:
list1 = []
,list2 = [0]
- Output:
[0]
Solution
To solve this problem, we can use a simple iterative approach. We will create two sorted lists, sortedList1
and sortedList2
, from the input lists list1
and list2
, respectively. Then, we will iterate through both lists and merge them into a single sorted list.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function(list1, list2) {
// Create a new list to store the merged result
const result = [];
let index = 0;
// Check if both lists are empty
if (!list1.length && !list2.length) return [];
// Sort both lists in ascending order
const sortedList1 = list1.sort((a, b) => a - b);
const sortedList2 = list2.sort((a, b) => a - b);
// Initialize two pointers, one for each list
let i = 0;
let j = 0;
// Merge the two sorted lists into a single list
while (i < sortedList1.length && j < sortedList2.length) {
// Compare the current elements of both lists
if (sortedList1[i] < sortedList2[j]) {
// If the current element of list1 is smaller, append it to the result
result.push(sortedList1[i]);
i++;
} else {
// If the current element of list2 is smaller, append it to the result
result.push(sortedList2[j]);
j++;
}
}
// Append any remaining elements from list1
while (i < sortedList1.length) {
result.push(sortedList1[i]);
i++;
}
// Append any remaining elements from list2
while (j < sortedList2.length) {
result.push(sortedList2[j]);
j++;
}
// Return the merged list
return result;
};
Explanation
The solution works by first sorting both input lists in ascending order. Then, it initializes two pointers, one for each list, and merges the two sorted lists into a single list. The merging process involves comparing the current elements of both lists and appending the smaller element to the result. Finally, the solution appends any remaining elements from both lists to the result and returns the merged list.
Time Complexity
The time complexity of the solution is O(n + m), where n and m are the lengths of the input lists. This is because the solution involves sorting both lists, which takes O(n log n) and O(m log m) time, respectively. Then, it merges the two sorted lists, which takes O(n + m) time.
Space Complexity
Q: What is the problem statement of the Merge Two Sorted Lists problem?
A: The problem statement is to merge two sorted linked lists, list1
and list2
, into one sorted list. The merged list should be created by splicing together the nodes of the first two lists.
Q: What are the constraints of the Merge Two Sorted Lists problem?
A: The constraints are:
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
.- Both
list1
andlist2
are sorted in non-decreasing order.
Q: What is the solution to the Merge Two Sorted Lists problem?
A: The solution involves sorting both input lists in ascending order, then merging the two sorted lists into a single list. The merging process involves comparing the current elements of both lists and appending the smaller element to the result.
Q: What is the time complexity of the solution?
A: The time complexity of the solution is O(n + m), where n and m are the lengths of the input lists. This is because the solution involves sorting both lists, which takes O(n log n) and O(m log m) time, respectively. Then, it merges the two sorted lists, which takes O(n + m) time.
Q: What is the space complexity of the solution?
A: The space complexity of the solution is O(n + m), where n and m are the lengths of the input lists. This is because the solution creates a new list to store the merged result, which requires O(n + m) space.
Q: How do I implement the Merge Two Sorted Lists solution in code?
A: You can implement the solution in code using the following steps:
- Sort both input lists in ascending order.
- Initialize two pointers, one for each list.
- Merge the two sorted lists into a single list by comparing the current elements of both lists and appending the smaller element to the result.
- Append any remaining elements from both lists to the result.
- Return the merged list.
Q: What are some common pitfalls to avoid when implementing the Merge Two Sorted Lists solution?
A: Some common pitfalls to avoid when implementing the solution include:
- Not sorting both input lists in ascending order before merging them.
- Not initializing two pointers, one for each list, before merging them.
- Not comparing the current elements of both lists correctly when merging them.
- Not appending any remaining elements from both lists to the result.
Q: How do I optimize the Merge Two Sorted Lists solution for large input lists?
A: You can optimize the solution for large input lists by using a more efficient sorting algorithm, such as quicksort or mergesort, instead of the built-in sort function. Additionally, you can use a more efficient data structure, such as a balanced binary search tree, to store the merged list.
Q: What are some real-world applications of the Merge Two Sorted Lists solution?
A: Some real-world applications of the solution include:
- Merging two sorted lists of data, such as customer information or product inventory.
- Creating a single sorted list from multiple sorted lists of data.
- Implementing a database query that requires merging two sorted lists of data.