Solving Leetcode Interviews in Seconds with AI: Remove Nth Node From End of List
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,
slowandfast, initialized to the head of the list. - Move the
fastpointernnodes ahead. This creates a gap ofnnodes betweenslowandfast. - Move both
slowandfastpointers simultaneously untilfastreaches the end of the list. At this point,slowwill be pointing to the node just before the node to be removed. Remove the next Node.
- Use two pointers,
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