EasyNo. 0021

Merge Two Sorted Lists — LeetCode 21 Python Solution

Topics
Recursion, Linked List
Reading time
3 min

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

PythonSolution
# 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 list2

Complexity

Time
O(m + n)
Space · auxiliary
O(m + n)

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

Related problems
No.ProblemDifficulty
0024Swap Nodes in PairsMedium
0025Reverse Nodes in k-GroupHard
0203Remove Linked List ElementsEasy
0206Reverse Linked ListEasy
0019Remove Nth Node From End of ListMedium
0061Rotate ListMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.