Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Reorder List

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "143" 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 head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … You may not modify the values in the list's nodes. Only nodes themselves may be changed. Example 1: Input: head = [1,2,3,4] Output: [1,4,2,3] Example 2: Input: head = [1,2,3,4,5] Output: [1,5,2,4,3] Constraints: The number of nodes in the list is in the range [1, 5 * 104]. 1 <= Node.val <= 1000

Explanation

Here's a solution to reorder the linked list as specified, along with an explanation:

  • Find the Middle: Locate the middle of the linked list using the slow and fast pointer approach.
  • Reverse the Second Half: Reverse the linked list starting from the middle node.
  • Merge the Two Halves: Merge the first and reversed second halves alternatively to achieve the desired reordering.

  • Time Complexity: O(N), where N is the number of nodes in the linked list.

  • Space Complexity: O(1)

Code

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

def reorderList(head):
    """
    Reorders the linked list in the specified L0 -> Ln -> L1 -> Ln-1 ... format.
    """

    if not head or not head.next:
        return

    # 1. Find the middle of the linked list
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    # 2. Reverse the second half of the linked list
    prev, curr = None, slow.next
    slow.next = None  # Break the list into two halves
    while curr:
        next_node = curr.next
        curr.next = prev
        prev = curr
        curr = next_node

    # 3. Merge the two halves
    first, second = head, prev
    while second:
        temp1, temp2 = first.next, second.next
        first.next = second
        second.next = temp1
        first, second = temp1, temp2

More from this blog

C

Chatmagic blog

2894 posts