Given the
Output: [1, 2]
Output: [1, 2, 3]
Since the list is sorted, all duplicate values are adjacent. We can traverse the list once,
and whenever the current node's value equals the next node's value, we skip the next node by
updating the
- Start with
curr = head . - While
curr != null andcurr.next != null : - If
curr.val == curr.next.val , skip the next node: setcurr.next = curr.next.next . - Otherwise, advance
curr = curr.next . - Return
head .
Complexity Analysis:
Time complexity: O(n) where n is the length of the list. Each node is visited at most once.
Space complexity: O(1) as only a single pointer is used for traversal.