Leetcode: Merge Sorted Lists

Rachit Gupta
1 min readDec 25, 2016

--

We need to merge 2 sorted linked lists using constant additional space. We can follow the steps listed below

  1. Initialize a dummy head
  2. While both lists are non-empty attach the node with smaller value to the result
  3. When one of the lists become empty attach the head of non-empty list to the result
  4. Return the 2nd node of the result as the first node was dummy

Remarks:

  1. O(1) space complexity as only 1 additional variable is used
  2. O(min(m.n)) time complexity where m and n are the lengths of the given list. This is because we only iterate until both lists are non-empty
  3. Used dummy head to avoid writing checks for empty input

Extensions:

  1. Merge k sorted lists
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
iter = res
while l1 and l2:
if l1.val < l2.val:
iter.next = l1
l1 = l1.next
else:
iter.next = l2
l2 = l2.next
iter = iter.next
if l1:
iter.next = l1
if l2:
iter.next = l2
return res.next

--

--