Remove Duplicates from Sorted List II
LeetCode 82 | Difficulty: Mediumβ
MediumProblem 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)β
| Metric | Value |
|---|---|
| Runtime | 166 ms |
| Memory | N/A |
| Date | 2017-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β
| Approach | Time | Space |
|---|---|---|
| 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.