Remove Duplicates from Sorted List

Drop adjacent duplicates from a sorted singly linked list with one pass.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
linked-list

Problem#

Given a sorted singly linked list, delete duplicates so each value appears only once.

Examples#

  • [1,1,2][1,2]
  • [1,1,2,3,3][1,2,3]

Constraints#

  • 0 <= n <= 300.

Approach#

Single pointer. If curr->val == curr->next->val, splice out curr->next; otherwise advance.

Solution#

Remove Duplicates from Sorted List
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* curr = head;
while (curr && curr->next) {
if (curr->val == curr->next->val) {
ListNode* del = curr->next;
curr->next = del->next;
delete del;
} else {
curr = curr->next;
}
}
return head;
}
};

Editorial#

Sorted invariant means duplicates are adjacent, so a single forward pointer suffices. Don’t advance after a splice — the new neighbor may also be a duplicate.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.