Remove duplicates from a sorted linked list
Problem
Given a sorted linked list, delete nodes so that each value appears only once.
Example 1
Input: 1 → 1 → 2 → 3 → 3 Output: 1 → 2 → 3
Also asked as: Remove Duplicates in a sorted Linked List
Test cases
Case 1
Input: [1,1,2,3,3] Expected: [1,2,3]
Case 2
Input: [1,1,1] Expected: [1]
Case 3
Input: [1,2,3] Expected: [1,2,3]
Case 4
Input: [] Expected: []
View solutionHide solution1 approach
1. Single pass — skip equal neighbours
Time O(n)Space O(1)
If the next node has the same value, unlink it.
function dedupeSorted(head) { let cur = head; while (cur && cur.next) { if (cur.next.val === cur.val) cur.next = cur.next.next; else cur = cur.next; } return head;}