Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created May 29, 2023 22:11
Show Gist options
  • Save Ifihan/346fad99be740d68aef0d665a176f35c to your computer and use it in GitHub Desktop.
Save Ifihan/346fad99be740d68aef0d665a176f35c to your computer and use it in GitHub Desktop.
Merge Two Sorted Lists

21. Merge Two Sorted Lists

Question: Leetcode - Easy

Approach

The approach to use two pointers: The first one was a dummy ListNode() and the second is a tail. Then I traverse throught the list by appending the smaller values of either lists in the tail pointer.

Once the end of the list is gotten to, I then append the remaining nodes to the linked list.

Then the next of the dummy node is returned which points to the first node of the merged linked list.

Code

# 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]:
        first = ListNode()
        second = first
        
        while list1 is not None and list2 is not None:
            if list1.val < list2.val:
                second.next = list1
                list1 = list1.next
            else:
                second.next = list2
                list2 = list2.next
                
            second = second.next
        
        second.next = list2 if list1 is None else list1
        return first.next

Complexities

  • Time Complexity: O(m + n) where m and n are the lengths of the linked list
  • Space Complexity: O(1) time is constant because I'm using a constant amount of space to store my dummy node and tail pointer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment