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 <= 100
list1
and list2
are sorted in non-decreasing order.Merging two sorted linked lists is a common problem in coding interviews and data structure applications. In this blog, we will discuss different approaches, analyze their time and space complexity, and provide an optimized solution.
Given two sorted linked lists, merge them into a single sorted linked list.
Input:
List1: 1 -> 3 -> 5
List2: 2 -> 4 -> 6
Output:
1 -> 2 -> 3 -> 4 -> 5 -> 6
1var mergeTwoLists = function(list1, list2) { 2 if (!list1) return list2; 3 if (!list2) return list1; 4 5 if (list1.val <= list2.val) { 6 list1.next = mergeTwoLists(list1.next, list2); 7 return list1; 8 } else { 9 list2.next = mergeTwoLists(list1, list2.next); 10 return list2; 11 } 12};
n
and m
are the sizes of the two lists)1var mergeTwoLists = function (list1, list2) { 2 let res = new ListNode(0); // Dummy node 3 let pointer = res; 4 5 while (list1 !== null && list2 !== null) { 6 if (list1.val <= list2.val) { 7 pointer.next = list1; 8 list1 = list1.next; 9 } else { 10 pointer.next = list2; 11 list2 = list2.next; 12 } 13 pointer = pointer.next; 14 } 15 16 // Attach the remaining nodes 17 pointer.next = list1 !== null ? list1 : list2; 18 19 return res.next; // Skip dummy node 20};
Approach | Time Complexity | Space Complexity | In-Place |
---|---|---|---|
Recursive | O(n + m) | O(n + m) (due to recursion) | ❌ No |
Iterative | O(n + m) | O(1) | ✅ Yes |
Hope this helps in understanding the problem and its solution! 🚀
Published by: Rakesh Reddy Peddamallu
Top Comments (0)