Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Merge In Between Linked Lists

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1669" 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 two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. Example 1: Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] Output: [10,1,13,1000000,1000001,1000002,5] Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. Example 2: Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] Output: [0,1,1000000,1000001,1000002,1000003,1000004,6] Explanation: The blue edges and nodes in the above figure indicate the result. Constraints: 3 <= list1.length <= 104 1 <= a <= b < list1.length - 1 1 <= list2.length <= 104

Explanation

Here's the breakdown of the solution:

  • Locate Insertion Points: Traverse list1 to find the nodes at positions a-1 and b+1. These will be the points where list2 needs to be inserted.
  • Link Lists: Connect the node at a-1 in list1 to the head of list2. Then, traverse list2 to find its tail. Connect the tail of list2 to the node at b+1 in list1.
  • Handle Edge Cases: Ensure the solution works correctly if a is 0 (insert at the beginning) or if b is the last element of list1

  • Time Complexity: O(n + m), where n is the length of list1 and m is the length of list2. Space Complexity: O(1) - constant extra space.

Code

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

def mergeInBetween(list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
    """
    Merges list2 into list1 between the ath and bth nodes of list1.
    """
    # Find the node before the insertion point (a-1)
    pre_a = list1
    for _ in range(a - 1):
        pre_a = pre_a.next

    # Find the node after the deletion point (b+1)
    post_b = list1
    for _ in range(b + 1):
        post_b = post_b.next

    # Connect list1 before 'a' to the head of list2
    pre_a.next = list2

    # Find the tail of list2
    tail_list2 = list2
    while tail_list2.next:
        tail_list2 = tail_list2.next

    # Connect the tail of list2 to list1 after 'b'
    tail_list2.next = post_b

    return list1

More from this blog

C

Chatmagic blog

2894 posts