Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Remove Nth Node From End of List

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "19" 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 linked list, remove the nth node from the end of the list and return its head. Example 1: Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Example 2: Input: head = [1], n = 1 Output: [] Example 3: Input: head = [1,2], n = 1 Output: [1] Constraints: The number of nodes in the list is sz. 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz Follow up: Could you do this in one pass?

Explanation

Here's the breakdown of the problem and the solution:

  • High-Level Approach:

    • Use two pointers, slow and fast, initialized to the head of the list.
    • Move the fast pointer n nodes ahead. This creates a gap of n nodes between slow and fast.
    • Move both slow and fast pointers simultaneously until fast reaches the end of the list. At this point, slow will be pointing to the node just before the node to be removed. Remove the next Node.
  • Complexity:

    • Runtime: O(N), where N is the number of nodes in the list (one pass).
    • Storage: O(1) (constant extra space).

Code

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

def removeNthFromEnd(head, n):
    """
    Removes the nth node from the end of a linked list.

    Args:
        head: The head of the linked list.
        n: The position of the node to remove from the end.

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

    # Create a dummy node to handle the case where the head needs to be removed.
    dummy = ListNode(0)
    dummy.next = head
    slow = dummy
    fast = head

    # Advance 'fast' pointer n nodes ahead
    for _ in range(n):
        if not fast:  # Handle edge case where n > list length. Although prompt specifies 1 <= n <= sz, it's good to include a sanity check
            return head
        fast = fast.next

    # Move both pointers until 'fast' reaches the end
    while fast:
        slow = slow.next
        fast = fast.next

    # Remove the nth node from the end
    slow.next = slow.next.next

    return dummy.next

More from this blog

C

Chatmagic blog

2894 posts