Skip to main content

Remove Duplicates from Sorted List II

LeetCode 82 | Difficulty: Medium​

Medium

Problem Description​

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.

Topics: Linked List, Two Pointers


Approach​

Linked List​

Use pointer manipulation. Common techniques: dummy head node to simplify edge cases, fast/slow pointers for cycle detection and middle finding, prev/curr/next pattern for reversal.

When to use

In-place list manipulation, cycle detection, merging lists, finding the k-th node.


Solutions​

Solution 1: C# (Best: 166 ms)​

MetricValue
Runtime166 ms
MemoryN/A
Date2017-09-20
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode DeleteDuplicates(ListNode head) {
if(head==null || head.next==null) return head;
ListNode temp = head;
ListNode dummy = new ListNode(Int32.MinValue);
dummy.next = head;
ListNode prev = dummy;
while (temp!= null && temp.next != null)
{
if (temp.val == temp.next.val)
{
var data = temp.val;
while (temp!= null && temp.val == data) { temp = temp.next; }
prev.next = temp;
}
else
{ prev.next = temp;
prev = temp;
if(temp!=null) temp = temp.next;
}

}
return dummy.next;
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$
Linked List$O(n)$$O(1)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Draw the pointer changes before coding. A dummy head node simplifies edge cases.