Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Odd Even Linked List

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "328" 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

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. Example 1: Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] Example 2: Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4] Constraints: The number of nodes in the linked list is in the range [0, 104]. -106 <= Node.val <= 106

Explanation

Here's a breakdown of the approach and the Python code:

  • Approach:

    • Maintain two pointers, one for odd nodes and one for even nodes.
    • Iterate through the list, connecting odd nodes together and even nodes together.
    • Finally, connect the tail of the odd nodes to the head of the even nodes.
  • Complexity:

    • O(n) time complexity, O(1) space complexity

Code

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

def oddEvenList(head: ListNode) -> ListNode:
    if not head:
        return head

    odd = head
    even = head.next
    even_head = even

    while even and even.next:
        odd.next = even.next
        odd = odd.next
        even.next = odd.next
        even = even.next

    odd.next = even_head

    return head

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Odd Even Linked List