Merge Two Sorted Lists

Problem Summary

What is Being Asked?

Key Observations

Approach Taken

Main Concepts Used

Time & Space Complexity

Code

class Solution:
    def mergeTwoLists(
        self, list1: Optional[ListNode], list2: Optional[ListNode]
    ) -> Optional[ListNode]:

        dummy = ListNode()
        p1, p2, cur = list1, list2, dummy

        while list1 and list2:
            if list1.val <= list2.val:
                cur.next = list1
                list1 = list1.next
            else:
                cur.next = list2
                list2 = list2.next
            cur = cur.next

        while list1:
            cur.next = list1
            list1 = list1.next
            cur = cur.next
        while list2:
            cur.next = list2
            list2 = list2.next
            cur = cur.next

        return dummy.next

Optimizations

We do not need to iterate through rest of the items. Its just pointers. We can set the next element to the remaining list.

if list1:
	cur.next = list1
else:
	cur.next = list2

Recursive Solution

class Solution:
    def mergeTwoLists(
        self, list1: Optional[ListNode], list2: Optional[ListNode]
    ) -> Optional[ListNode]:
        if not list1 or not list2:
            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