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:
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]
Constraints:
[0, 50].-100 <= Node.val <= 100list1 and list2 are sorted in non-decreasing order.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:
Imagine you have two separate piles of cards, and each pile is already sorted from smallest to largest. The brute force strategy involves gathering all the cards from both piles together into one big mixed pile, and then sorting the whole thing from scratch.
Here's how the algorithm would work step-by-step:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list_node_one, list_node_two):
unsorted_collection = []
current_node_one = list_node_one
while current_node_one is not None:
unsorted_collection.append(current_node_one.val)
current_node_one = current_node_one.next
current_node_two = list_node_two
while current_node_two is not None:
unsorted_collection.append(current_node_two.val)
current_node_two = current_node_two.next
# Gather all elements from both lists into a single workspace before sorting
unsorted_collection.sort()
dummy_head_node = ListNode()
current_tail_node = dummy_head_node
# Build a new sorted list by sequentially extracting the smallest elements
for element_value in unsorted_collection:
current_tail_node.next = ListNode(element_value)
current_tail_node = current_tail_node.next
# Return the newly constructed list starting from the node after dummy head
return dummy_head_node.nextInstead of scrambling everything together and sorting it at the very end, we can build the final sorted list progressively by comparing the front of both lists one step at a time. By always picking the smaller of the two front items and moving forward, we naturally weave them together into a single sorted chain.
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 merge_two_lists(first_sorted_list, second_sorted_list):
dummy_start_node = ListNode()
current_tail_node = dummy_start_node
# Compare front items to weave lists together in sorted order step-by-step.
while first_sorted_list is not None and second_sorted_list is not None:
if first_sorted_list.val <= second_sorted_list.val:
current_tail_node.next = first_sorted_list
first_sorted_list = first_sorted_list.next
else:
current_tail_node.next = second_sorted_list
second_sorted_list = second_sorted_list.next
current_tail_node = current_tail_node.next
# Attach remaining items since the other list has been completely exhausted.
if first_sorted_list is not None:
current_tail_node.next = first_sorted_list
else:
current_tail_node.next = second_sorted_list
return dummy_start_node.next| Case | How to Handle |
|---|---|
| Both input lists are completely empty or null | Returning null immediately avoids null pointer exceptions and correctly outputs an empty merged list. |
| One of the input lists is empty while the other contains elements | The algorithm attaches the non-empty list directly to the result, preserving all its remaining nodes. |
| Lists contain only a single node each | The comparison correctly links the smaller node to the larger one and terminates without extra iterations. |
| Lists contain duplicate values across or within lists | Stable splicing logic ensures nodes with equal values are placed consecutively without overwriting. |
| Input lists contain negative numbers, zeros, and positive integers | Standard numerical comparison handles mixed signs correctly since order goes from most negative to positive. |
| One list is significantly longer or contains all elements smaller than the other list | An iterative approach processes the remainder in linear time without risking call stack overflow. |
| Recursive implementation with extremely long linked lists | Iterative merging with a dummy node should be preferred over recursion to prevent exceeding call stack limits. |
| Memory management in languages with manual memory control | Nodes are safely reassigned by reference without allocating new memory, preventing memory leaks. |