Last updated on January 20th, 2025 at 10:52 pm
Here, we see a Merge Two Sorted Lists LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Linked List
Companies
Amazon, Apple, LinkedIn, Microsoft
Level of Question
Easy
Merge Two Sorted Lists LeetCode Solution
Table of Contents
1. Problem Statement
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a 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: (fig-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]
2. Coding Pattern Used in Solution
The coding pattern used in the provided code is “K-way Merge”. This pattern is commonly used to merge multiple sorted lists or arrays into a single sorted list. In this case, the problem involves merging two sorted linked lists into one sorted linked list.
3. Code Implementation in Different Languages
3.1 Merge Two Sorted Lists C++
class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { if(list1 == NULL) return list2; if(list2 == NULL) return list1; if(list1->val>=list2->val) list2->next = mergeTwoLists(list1, list2-> next); else{ list1->next = mergeTwoLists(list1->next, list2); list2 = list1; }return list2; } };
3.2 Merge Two Sorted Lists Java
class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { if(list1 == null) return list2; if(list2 == null) return list1; if(list1.val < list2.val){ list1.next = mergeTwoLists(list1.next, list2); return list1; } else{ list2.next = mergeTwoLists(list1, list2.next); return list2; } } }
3.3 Merge Two Sorted Lists JavaScript
var mergeTwoLists = function(list1, list2) { var mergedHead = { val : -1, next : null }, crt = mergedHead; while(list1 && list2) { if(list1.val > list2.val) { crt.next = list2; list2 = list2.next; } else { crt.next = list1; list1 = list1.next; } crt = crt.next; } crt.next = list1 || list2; return mergedHead.next; };
3.4 Merge Two Sorted Lists Python
class Solution(object): def mergeTwoLists(self, list1, list2): dummy = cur = ListNode(0) while list1 and list2: if list1.val < list2.val: cur.next = list1 list1 = list1.next else: cur.next = list2 list2 = list2.next cur = cur.next cur.next = list1 or list2 return dummy.next
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n + m) | O(n + m) |
Java | O(n + m) | O(n + m) |
JavaScript | O(n + m) | O(1) |
Python | O(n + m) | O(1) |