Problem Description
Given the head of a sorted linked list, delete all duplicates such that each element appears only once and return the sorted linked list.
Key Insights
- The linked list is already sorted, so any duplicates will be adjacent.
- A single pass through the list is sufficient to remove duplicates.
- The algorithm modifies the list in place without needing extra memory.
Space and Time Complexity
Time Complexity: O(n) - where n is the number of nodes in the list
Space Complexity: O(1) - in-place modification with constant extra space
Solution
We traverse the linked list using a pointer. For each node, we check if the next node has the same value. If it does, we adjust the pointer to skip the duplicate node. Otherwise, we move our pointer to the next node. This approach efficiently removes duplicates in a single pass without requiring additional data structures.