Solving Leetcode Interviews in Seconds with AI: Remove Duplicates from Sorted List II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "82" 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 sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: head = [1,2,3,3,4,4,5] Output: [1,2,5] Example 2: Input: head = [1,1,1,2,3] Output: [2,3] Constraints: The number of nodes in the list is in the range [0, 300]. -100 <= Node.val <= 100 The list is guaranteed to be sorted in ascending order.
Explanation
Here's the breakdown of the solution:
- Iterate and Identify Duplicates: Traverse the linked list, identifying consecutive nodes with the same value.
- Skip Duplicates: When duplicates are found, advance the pointer until a distinct value is encountered, effectively removing the duplicate range.
Maintain List Structure: Use a dummy head to simplify handling the beginning of the list and to properly link the remaining distinct nodes.
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 deleteDuplicates(head):
"""
Given the head of a sorted linked list, delete all nodes that have duplicate
numbers, leaving only distinct numbers from the original list. Return the
linked list sorted as well.
"""
dummy = ListNode(0) # Dummy node to handle edge cases at the beginning
dummy.next = head
prev = dummy
curr = head
while curr:
if curr.next and curr.val == curr.next.val:
# Found duplicates, skip all of them
while curr.next and curr.val == curr.next.val:
curr = curr.next
prev.next = curr.next # Skip the entire duplicate sequence
else:
prev = curr # No duplicates, move prev forward
curr = curr.next # Move curr forward
return dummy.next