Leetcode 82. Remove Duplicates from Sorted List II
You are given the head of a sorted linked list. Remove all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Input: head = [1,1,1,2,3]
Output: [2,3]
To solve this problem:
Here is the code implementation in Java:
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
ListNode dummy = new ListNode(0, head);
ListNode pred = dummy; // predecessor, the last node before the sublist of duplicates
while (head != null) {
if (head.next != null && head.val == head.next.val) {
// Skip nodes whose value are the same as the current node's value
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
pred.next = head.next;
} else {
pred = pred.next;
}
head = head.next;
}
return dummy.next;
}
}
The time complexity for this solution is O(n) because:
The space complexity is O(1) because:
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?