Remove Duplicates From Sorted List


83. Remove Duplicates from Sorted List – LeetCode


Problem Statement

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.


Examples

Example 1:

Input: head = [1,1,2]
Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]
Output: [1,2,3]

Constraints


Intuition

Since the list is already sorted, duplicate elements will always appear consecutively.
We just need to compare current node with the next node, and skip the next node if it's a duplicate.


Approach

  1. Start from the head of the list.

  2. While the current node and the next node are not null:

    • If node.val == node.next.val, skip the next node by adjusting the pointer: node.next = node.next.next

    • Else, move to the next node.

  3. Return the head of the modified list.


Java Code

class Solution {
    public ListNode deleteDuplicates(ListNode node) {
        if (node == null) return null;

        ListNode head = node;

        while (node.next != null) {
            if (node.val == node.next.val) {
                node.next = node.next.next; // Skip the duplicate
            } else {
                node = node.next; // Move to next distinct node
            }
        }

        return head;
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)
Explanation Only one pass through the list, no extra memory used

Dry Run

Input:

head = [1,1,2,3,3]

Step-by-step:

Final list: [1,2,3]


Conclusion

This problem demonstrates a classic use of pointer manipulation in singly linked lists. Since the list is sorted, the solution becomes simple and efficient using a single traversal.