Merge Two Sorted Lists - Leetcode Solution - CodingBroz (2024)

In this post, we are going to solve the 21. Merge Two Sorted Lists problem of Leetcode. This problem 21. Merge Two Sorted Lists is a Leetcode easy level problem. Let’s see the code, 21. Merge Two Sorted Lists – Leetcode Solution.

Problem

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 :

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

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

Now, let’s see the code of 21. Merge Two Sorted Lists – Leetcode Solution.

21. Merge Two Sorted Lists – Solution in Java

This is the Iterative Approach to the solution of 21. Merge Two Sorted Lists in Java Programming Language.

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode handler = head; while(l1 != null && l2 != null) { if (l1.val <= l2.val) { handler.next = l1; l1 = l1.next; } else { handler.next = l2; l2 = l2.next; } handler = handler.next; } if (l1 != null) { handler.next = l1; } else if (l2 != null) { handler.next = l2; } return head.next; }}

Now let’s see the Recursive approach to solve the same problem in Java using Recursion.

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode handler; if(l1.val < l2.val) { handler = l1; handler.next = mergeTwoLists(l1.next, l2); } else { handler = l2; handler.next = mergeTwoLists(l1, l2.next); } return handler; }}

21. Merge Two Sorted Lists – Solution in C++

This is the Iterative Approach to the solution of 21. Merge Two Sorted Lists in C++ Programming Language.

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */class Solution {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* temp = new ListNode(-1); ListNode* head = temp; while(l1!=NULL and l2!=NULL){ if(l1->val<=l2->val){ head->next = l1; l1 = l1->next; } else { head->next = l2; l2 = l2->next; } head=head->next; } if(l1!=NULL) { head->next = l1; } else head->next = l2; return temp->next; }};

Now let’s see the Recursive approach to solve the same problem in C++ using Recursion.

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */class Solution {public:ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {if(l1 == NULL) {return l2;}if(l2 == NULL) {return l1;} if(l1 -> val <= l2 -> val) {l1 -> next = mergeTwoLists(l1 -> next, l2);return l1;}else {l2 -> next = mergeTwoLists(l1, l2 -> next);return l2; }}};

21. Merge Two Sorted Lists – Solution in Python

This is the Iterative Approach to the solution of 21. Merge Two Sorted Lists in Python Programming Language.

# Definition for singly-linked list.# class ListNode(object):# def __init__(self, val=0, next=None):# self.val = val# self.next = nextdef mergeTwoLists1(self, l1, l2): dummy = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dummy.next

Now let’s see the Recursive approach to solve the same problem in Python using Recursion.

# Definition for singly-linked list.# class ListNode(object):# def __init__(self, val=0, next=None):# self.val = val# self.next = nextdef mergeTwoLists2(self, l1, l2): if not l1 or not l2: return l1 or l2 if l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2

Note: This problem 21. Merge Two Sorted Lists is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Related

Merge Two Sorted Lists - Leetcode Solution - CodingBroz (2024)

FAQs

How do I combine two lists in sorted order? ›

Sort and Merge Two Lists using sort() Method
  1. Define the two variables to assign the empty lists.
  2. Now takes the number of inputs for the first and second list.
  3. Now merge both lists using the '+' operator.
  4. Use the built-in sort() method to sort the newly created list.

How do I merge sort lists? ›

A merge sort uses a technique called divide and conquer. The list is repeatedly divided into two until all the elements are separated individually. Pairs of elements are then compared, placed into order and combined. The process is then repeated until the list is recompiled as a whole.

How do you combine two sorted linked list algorithms? ›

Merge two sorted linked lists by Reversing the Lists:
  1. Set 'temp' to point to the 'head2. next' node.
  2. Update 'head2. next' to the current 'res' node.
  3. Update 'res' to point to 'head2'.
  4. Move 'head2' to the node stored in 'temp'.
  5. After completing the loop, return the 'res' node, representing the merged linked list.
Mar 27, 2024

How to merge two sorted lists in C++? ›

C++ Program To Merge Two Sorted Lists (In-Place)
  1. Compare the head of both linked lists.
  2. Find the smaller node among the two head nodes. ...
  3. The rest elements of both lists will appear after that.
  4. Now run a recursive function with parameters, the next node of the smaller element, and the other head.
Aug 17, 2023

How do I combine two lists into one? ›

Method 1.

The first list contains integer values while the second contains string values. To concatenate the two lists, use the + operator. The code below combines the two strings and stores the result in a new list called combined_list . You can confirm the contents of the new list using the print statement.

How do I merge two unsorted lists? ›

Merge two unsorted linked lists to get a sorted list
  1. Concatenate the two lists by traversing the first list until we reach it's a tail node and then point the next of the tail node to the head node of the second list. Store this concatenated list in the first list.
  2. Sort the above-merged linked list.
Dec 27, 2021

How do I combine merge sorts? ›

Merge sort is a divide-and-conquer algorithm based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element and merging those sublists in a manner that results into a sorted list. Idea: Divide the unsorted list into sublists, each containing element.

Why is merge sort bad for small lists? ›

For small datasets, merge sort is slower than other sorting algorithms. For the temporary array, mergesort requires an additional space of O(n). Even if the array is sorted, the merge sort goes through the entire process.

What is the time required to merge two sorted lists? ›

The time complexity for this solution is O(n + m), where n and m are the lengths of l1 and l2 respectively. This is because in the worst case, we would need to iterate through all elements in both lists. The space complexity is O(1), as we are only using a constant amount of space to store the head and prev nodes.

How do you combine two sorted array algorithms? ›

Algorithm
  1. Start the program.
  2. Input the length of both the arrays.
  3. Input the arrays elements from user.
  4. Copy the elements of the first array to the merged array when initialising it.
  5. Copy the elements of the second array to the merged array while initialising the second array.
  6. Sort the merged array now.
Mar 27, 2024

How do you merge two lists sorted in Python? ›

Approach: Using itertools.chain() and sorted()
  1. Import itertools library.
  2. Initialize two sorted lists.
  3. Use itertools. chain() method to merge both lists.
  4. Use the sorted() method to sort the merged list.
  5. Print the sorted and merged list.
May 2, 2023

How to merge two sorted lists into a single list? ›

Step 1:Initialise an empty array and iterate through each node of the first and second linked list adding them to the array. Step 2: Sort the array in ascending order, using a sorting algorithm like quick sort, merge sort or the inbuilt library.

How do I merge two sorted lists recursively? ›

Approach 2: Recursive

Compare the values of the heads of the two lists. Set the smaller value as the head of the merged list. Recursively call the function with the next node of the list that had the smaller value. Set the next pointer of the merged list to the result of the recursive call.

What is the function to merge two lists in C++? ›

The list::merge() is an inbuilt function in C++ STL which merges two sorted lists into one. The lists should be sorted in ascending order. If no comparator is passed in parameter, then it merges two sorted lists into a single sorted list.

What is the process of combining two sorted sequences called? ›

In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, and comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the relative order of equal elements is the same in the input and output.

How do I merge two sorted queues? ›

1) Make pointers for both of the queues. 2) Make another queue, add the node having least value from the other two queues(the pointer's node having the smallest value) to it and move that pointer to the next node.

How do I merge two arrays in sorted form? ›

Approach 1
  1. Suppose the size of 'ARR1' is 'M' and the size of 'ARR2' is 'N'. ...
  2. Copy the elements from 'ARR1' to 'ARR3'.
  3. Copy the elements from 'ARR2' to 'ARR3'.
  4. Sort the array, 'ARR3'.
  5. Copy the first 'M' elements from 'ARR3' to 'ARR1' and copy the remaining 'N' elements from 'ARR3' to 'ARR2'.
Mar 27, 2024

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5934

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.