Merge Two Sorted Lists
The problem description can be found in LeetCode.
Approach
It is very easy to think on a recursive approach here. In fact, we should take:
- list1[0]+- merge(list1[1:], list2)if- list1[0] < list2[0].
- list2[0]+- merge(list1, list2[1:])if- list1[0] >= list2[0].
Solution
from typing import Optional
class Solution:
    def mergeTwoLists(
        self, list1: Optional[ListNode], list2: Optional[ListNode]
    ) -> Optional[ListNode]:
        if not list1 and not list2:
            return None
        if not list1:
            return list2
        if not list2:
            return list1
        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:
- Space:
Where  and  are the sizes of the list1 and list2 lists, respectively.