Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Swapping Nodes in a Linked List

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1721" 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 linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5] Example 2: Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 Output: [7,9,6,6,8,7,3,0,9,5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 105 0 <= Node.val <= 100

Explanation

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

  • High-Level Approach:

    • Find the kth node from the beginning.
    • Find the kth node from the end using two pointers.
    • Swap the values of these two nodes.
  • Complexity:

    • Runtime: O(n), where n is the number of nodes in the linked list.
    • Storage: O(1) - constant extra space.

Code

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

 def swapNodes(head: ListNode, k: int) -> ListNode:
     """
     Swaps the values of the kth node from the beginning and the kth node from the end of a linked list.

     Args:
         head: The head of the linked list.
         k: The index of the nodes to swap (1-indexed).

     Returns:
         The head of the modified linked list.
     """

     # Find the kth node from the beginning
     first = head
     for _ in range(k - 1):
         first = first.next

     # Find the kth node from the end using two pointers
     slow = head
     fast = head
     for _ in range(k):
         fast = fast.next

     while fast:
         slow = slow.next
         fast = fast.next

     second = slow

     # Swap the values
     first.val, second.val = second.val, first.val

     return head

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Swapping Nodes in a Linked List