You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
list1
= [1,2,4], list2
= [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
list1
= [], list2
= []
Output: []
Example 3:
list1
= [], list2
= [0]
Output: [0]
Can you implement a function that merges two sorted linked lists into a single sorted linked list? Consider edge cases such as empty lists. What is the time and space complexity of your solution?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method for merging two sorted lists involves exhaustively comparing elements from both lists and building a completely new merged list. We essentially explore every possible combination of elements to find the correct sorted order. This is like manually sorting a shuffled deck of cards by constantly comparing pairs and rearranging them.
Here's how the algorithm would work step-by-step:
def merge_two_sorted_lists_brute_force(list1, list2):
merged_list = []
while list1 and list2:
# Compare the first elements of both lists.
if list1[0] <= list2[0]:
merged_list.append(list1[0])
list1.pop(0)
else:
merged_list.append(list2[0])
list2.pop(0)
# If list1 has remaining elements, add them.
if list1:
# List1 still contains elements
merged_list.extend(list1)
# If list2 has remaining elements, add them.
if list2:
# List2 still contains elements
merged_list.extend(list2)
return merged_list
We're given two sorted lists and need to combine them into one sorted list. The key idea is to avoid unnecessary comparisons by always picking the smallest element from the heads of the two lists to build our final sorted list. This ensures we build the merged list in the correct order efficiently.
Here's how the algorithm would work step-by-step:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(list1, list2):
# Create a dummy node to simplify the head insertion.
dummy_node = ListNode()
tail_node = dummy_node
while list1 and list2:
# Pick the smaller value node and advance.
if list1.val <= list2.val:
tail_node.next = list1
list1 = list1.next
else:
tail_node.next = list2
list2 = list2.next
tail_node = tail_node.next
# Attach the remaining elements of the other list
if list1:
tail_node.next = list1
if list2:
tail_node.next = list2
return dummy_node.next
Case | How to Handle |
---|---|
Both lists are null | Return null immediately as there is nothing to merge. |
One list is null, the other is not | Return the non-null list as the merged list. |
One or both lists contain only one node | The iterative merging process should correctly handle lists with only one node by simply appending it at the correct position. |
Both lists contain the same single value | The iterative process correctly appends both nodes in sorted order. |
Lists contain many duplicate values (e.g., many 1's, many 2's) | The iterative approach handles duplicate values without issue, as it compares node values directly. |
All values in list1 are smaller than all values in list2 | The iterative comparison correctly appends all list1 nodes before appending list2 nodes. |
List1 is much longer than list2 (or vice versa) | The while loop condition accounts for only one of the list reaching the end, appends the other longer list. |
List elements contain negative numbers, zeros, and large positive numbers | The iterative comparison should work regardless of the value, as long as they are comparable. |