Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Merge Two Sorted Lists

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "21" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. Example 1: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: list1 = [], list2 = [] Output: [] Example 3: Input: list1 = [], list2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both list1 and list2 are sorted in non-decreasing order.

Explanation

Here's the solution to merge two sorted linked lists:

  • Iterative Approach: The solution uses an iterative approach to traverse both lists simultaneously. A new list is created by comparing the current nodes of list1 and list2, and appending the smaller node to the new list.
  • Dummy Node: A dummy node is used as the starting point of the merged list, simplifying the handling of the head.
  • Splicing: The nodes are spliced together which means that no new nodes are created, but rather the existing nodes from the input lists are rearranged to form the merged list.

  • Time Complexity: O(m+n), where m and n are the lengths of list1 and list2 respectively. Space Complexity: O(1).

Code

    class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeTwoLists(list1, list2):
    """
    Merges two sorted linked lists into one sorted list.

    Args:
        list1: The head of the first sorted linked list.
        list2: The head of the second sorted linked list.

    Returns:
        The head of the merged sorted linked list.
    """

    dummy = ListNode()  # Dummy node to simplify head handling
    tail = dummy  # Tail of the merged list

    while list1 and list2:
        if list1.val <= list2.val:
            tail.next = list1
            list1 = list1.next
        else:
            tail.next = list2
            list2 = list2.next
        tail = tail.next

    # Append the remaining nodes from either list (if any)
    if list1:
        tail.next = list1
    elif list2:
        tail.next = list2

    return dummy.next  # Return the head of the merged list (after the dummy node)

More from this blog

C

Chatmagic blog

2894 posts