|
| 1 | +# 21 - Merge Two Sorted Lists |
| 2 | + |
| 3 | +Difficulty: easy |
| 4 | +Done: Yes |
| 5 | +Last edited: March 2, 2022 1:53 AM |
| 6 | +Link: https://leetcode.com/problems/merge-two-sorted-lists/submissions/ |
| 7 | +Topic: linked list |
| 8 | + |
| 9 | +## Problem |
| 10 | + |
| 11 | +--- |
| 12 | + |
| 13 | +You are given the heads of two sorted linked lists `list1` and `list2`. Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. |
| 14 | + |
| 15 | +Return *the head of the merged linked list*. |
| 16 | + |
| 17 | +``` |
| 18 | +Input: list1 = [1,2,4], list2 = [1,3,4] |
| 19 | +Output: [1,1,2,3,4,4] |
| 20 | +``` |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +## Solution |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +Solution can be done in a single iterative traversal, resulting in linear time complexity. To do so we would need to traverse both lists with the use of a pointer —*previous—* which essentially tracks the current place in the final list. |
| 29 | + |
| 30 | +Additionally we would need to add a sentinel node (hypothetical first node). This allows to functionally make the final merged list never empty. |
| 31 | + |
| 32 | +The while loop —typical for linked list problems— only runs while l1 or l2 do not point to None. Since |
| 33 | + |
| 34 | +## Whiteboard |
| 35 | + |
| 36 | +--- |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +## Code |
| 41 | + |
| 42 | +--- |
| 43 | + |
| 44 | +```python |
| 45 | +# Definition for singly-linked list. |
| 46 | +# class ListNode: |
| 47 | +# def __init__(self, val=0, next=None): |
| 48 | +# self.val = val |
| 49 | +# self.next = next |
| 50 | +class Solution: |
| 51 | + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: |
| 52 | + |
| 53 | + # create sentinel node |
| 54 | + s = ListNode(0, None) |
| 55 | + previous = s |
| 56 | + |
| 57 | + while list1 is not None and list2 is not None: |
| 58 | + # compare value at l1 vs value at l2 |
| 59 | + # whichever is smaller that's where we point previous, and step that list |
| 60 | + # essentially prev keeps track of the new list |
| 61 | + |
| 62 | + if list1.val <= list2.val: |
| 63 | + previous.next = list1 |
| 64 | + list1 = list1.next |
| 65 | + else: |
| 66 | + previous.next = list2 |
| 67 | + list2 = list2.next |
| 68 | + |
| 69 | + previous = previous.next |
| 70 | + |
| 71 | + # the while loop only runs while l1 or l2 are not None |
| 72 | + |
| 73 | + # since lists can be diffent sizes, |
| 74 | + # when we've reached the end for one we can point |
| 75 | + # the merged list to the non-null list |
| 76 | + previous.next = list1 or list2 |
| 77 | + |
| 78 | + return s.next |
| 79 | +``` |
| 80 | + |
| 81 | +## Time Complexity |
| 82 | + |
| 83 | +--- |
| 84 | + |
| 85 | +big O |
0 commit comments