Merge Two Sorted Lists — LeetCode 21 Python Solution
- Problem
- #21
- Pattern
- Linked List
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list.
Example
- Input
- list1 = [1,2,4], list2 = [1,3,4]
- Output
- [1,1,2,3,4,4]
Python solution
# 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, list1: Optional[ListNode], list2: Optional[ListNode]
) -> Optional[ListNode]:
if list1 is None or list2 is None:
return list1 or list2
if list1.val <= list2.val:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
else:
list2.next = self.mergeTwoLists(list1, list2.next)
return list2Complexity
| Measure | Complexity |
|---|---|
| Time | O(m + n) |
| Space | O(m + n) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 21. Merge Two Sorted Lists is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 21. Merge Two Sorted Lists?
- LeetCode 21. Merge Two Sorted Lists is rated Easy on LeetCode.
- What is the time complexity of LeetCode 21. Merge Two Sorted Lists?
- The Python solution on this page runs in O(m + n).
- What is the space complexity of LeetCode 21. Merge Two Sorted Lists?
- The Python solution on this page uses O(m + n) auxiliary space.
- What topics does LeetCode 21. Merge Two Sorted Lists cover?
- LeetCode 21. Merge Two Sorted Lists is tagged Recursion and Linked List on LeetCode.