7.6 Remove Duplicates from Sorted List
7.6.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 83
- Difficulty: Easy
- URL: https://leetcode.com/problems/remove-duplicates-from-sorted-list/
- Techniques: Linked List
7.6.2 Description
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.
7.6.4 Constraints
- The number of nodes is in the range
[0, 300] -100 <= Node.val <= 100- The list is guaranteed to be sorted in ascending order
7.6.5 Solution - In-Place Skip
7.6.5.1 Walkthrough
Since the list is sorted, duplicates are always adjacent. We simply traverse and skip over duplicate nodes.
Core Strategy:
- For each node, compare its value with the next node’s value
- If equal, skip the next node by updating
curr.next - If different, move to the next node
Example: Remove duplicates from [1,1,2,3,3]:
curr at 1: curr.val (1) == curr.next.val (1) → skip: 1 → 2 → 3 → 3
curr at 1: curr.val (1) != curr.next.val (2) → move curr to 2
curr at 2: curr.val (2) != curr.next.val (3) → move curr to 3
curr at 3: curr.val (3) == curr.next.val (3) → skip: 1 → 2 → 3 → null
curr at 3: curr.next is null → done
Result: [1,2,3]
7.6.5.2 Analysis
- Time Complexity: O(n) - Each node visited at most once
- Space Complexity: O(1) - Only pointer variables used