Opening the reading…
Opening the reading…
LINKED LIST › LINKED LIST (PART 1)
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A sorted list places equal values next to one another, so duplicates form consecutive runs such as 1, 1, 1 or 3, 3. For each run, the first node is the one you keep. Every later node has the same value as the node immediately before it, so it can be removed without searching elsewhere in the list.
Keep a pointer named current at the last node that remains in the answer. Compare current with current->next. If their values match, bypass current->next and leave current where it is, because another duplicate may still follow. If they differ, current is already the last kept node for its value, so advance it.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | current moves forward at most n - 1 times, and each duplicate is unlinked once. A node is never revisited after current passes it, so the total number of comparisons and pointer changes is linear. |
| Space | O(1) extra | Only current and one temporary pointer are used, regardless of the list shape. The returned list is required output and is excluded from the extra-space bound; the input is already a single chain, so there is no deeper worst case to add. |
#include <cstddef>
using namespace std;
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return nullptr;
ListNode* current = head;
while (current && current->next) {
if (current->val == current->next->val) {
ListNode* duplicate = current->next;
current->next = current->next->next;
delete duplicate;
} else {
current = current->next;
}
}
return head;
}
};The placement of current = current->next is the central detail. It belongs only in the unequal branch. After removing one duplicate, current may still be followed by another equal node, so advancing immediately would leave part of a duplicate run in the list. The temporary pointer is deleted after the link is redirected, which preserves the suffix before releasing the removed node.