0021. Merge Two Sorted Lists
Easy | Linked List + Recursion | 16ms (98.84%), 13.4 MB (87.61%)
Source: LeetCode - Merge Two Sorted Lists GitHub: Solution / Performance
Merge two sorted linked lists and return them as a sorted list. The list should be made by "splicing" together (with) the nodes of the first two lists.
Therefore, top-down recursion could help us sort by in-place modification on either l1 or l2 as a starting node.
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# (base case)
if not l2 and l1: return l1
if not l1 and l2: return l2
if not l1 and not l2: return None
# ==================================================
# Linked List + Recursion =
# ==================================================
# n is the length of l1, and m is the length of l2
# time : O(n+m)
# space : O(n+m)
if l1.val > l2.val: l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
Last updated
Was this helpful?