21_Merge Two Sorted Lists

[easy] [linked list]

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Solution: Iterative

Idea:

  • Initialize the head node, continue linking to nodes with smallest values

Time Complexity: O(m+n)O(m+n)

Space Complexity: O(1)O(1)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

def mergeTwoLists(l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """    
    # iteratively, in-place
    dummy_head = cur = ListNode(0)
    while l1 and l2:
        if l1.val < l2.val:
            cur.next = l1
            l1 = l1.next
        else:
            cur.next = l2
            l2 = l2.next
        cur = cur.next

    # Appending the remaining nodes of l1 or l2
    cur.next = l1 or l2
    return dummy_head.next

Solution: Recursive

Idea:

  • Time Complexity: O(m+n)O(m+n)

Space Complexity: O(1)O(1)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

def mergeTwoLists(l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """    

    # recursively, in-place    
    if not l1 or not l2:
        return l1 or l2
    if l1.val < l2.val:
        l1.next = mergeTwoLists(l1.next, l2)
        return l1
    else:
        l2.next = mergeTwoLists(l1, l2.next)
        return l2

Last updated