Leetcode 21: Merge Two Sorted Lists

grid47
grid47
Exploring patterns and algorithms
Nov 4, 2024 5 min read

Two glowing lists merging, with soft energy flowing together in sync.
Solution to LeetCode 21: Merge Two Sorted Lists Problem

Given two sorted linked lists, merge them into one sorted linked list by splicing together the nodes from both lists. Return the head of the merged linked list.
Problem
Approach
Steps
Complexity
Input: You are given two sorted linked lists, list1 and list2. Each list is sorted in non-decreasing order and contains a series of nodes.
Example: list1 = [5,10,15], list2 = [1,7,12]
Constraints:
• The number of nodes in each list is between 0 and 50.
• -100 <= Node.val <= 100
• Both lists are sorted in non-decreasing order.
Output: Return the head of the new sorted linked list formed by merging the two input lists.
Example: Output: [1,5,7,10,12,15]
Constraints:
Goal: Merge two sorted linked lists into a single sorted list.
Steps:
• Initialize a dummy node to help with list manipulation.
• Use two pointers to traverse through both linked lists, comparing nodes at each step.
• Append the smaller node to the result list and move the corresponding pointer.
• After one of the lists is exhausted, append the remaining nodes from the other list.
Goal: The constraints ensure that the input lists are within reasonable bounds for processing.
Steps:
• The number of nodes in each list is in the range [0, 50].
• -100 <= Node.val <= 100
• Both list1 and list2 are sorted in non-decreasing order.
Assumptions:
• The input lists are sorted in non-decreasing order.
• There are no cycles in the linked lists.
Input: Example 1
Explanation: In this example, the lists [5,10,15] and [1,7,12] are merged to form the sorted list [1,5,7,10,12,15].

Input: Example 2
Explanation: When one of the lists is empty, as in the case of list1 = [] and list2 = [3,8], the result is just the other list: [3,8].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus