LeetCode 82: Remove Duplicates from Sorted List II Solution

Master LeetCode problem 82 (Remove Duplicates from Sorted List II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

82. Remove Duplicates from Sorted List II

Problem Explanation

Explanation

To solve this problem, we will traverse the linked list while keeping track of duplicate nodes. We will maintain three pointers: prev, curr, and next. We will iterate over the list, checking if the current node's value is equal to the next node's value. If duplicates are found, we will skip over all duplicates by adjusting the pointers appropriately. If no duplicates are found, we will move the pointers forward accordingly.

At the end of the process, we will have removed all duplicates and kept only distinct numbers in the linked list.

  • Time complexity: O(n) where n is the number of nodes in the linked list.
  • Space complexity: O(1)

Solution Code

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode curr = head;
        
        while (curr != null) {
            boolean isDuplicate = false;
            while (curr.next != null && curr.val == curr.next.val) {
                curr = curr.next;
                isDuplicate = true;
            }
            
            if (isDuplicate) {
                prev.next = curr.next;
            } else {
                prev = prev.next;
            }
            
            curr = curr.next;
        }
        
        return dummy.next;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 82 (Remove Duplicates from Sorted List II)?

This page provides optimized solutions for LeetCode problem 82 (Remove Duplicates from Sorted List II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 82 (Remove Duplicates from Sorted List II)?

The time complexity for LeetCode 82 (Remove Duplicates from Sorted List II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 82 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 82 in Java, C++, or Python.

Back to LeetCode Solutions