This problem requires removing nodes from a linked list that contain values which appear more than once in the list. The solution uses a hash table (or dictionary in Python) to efficiently count the occurrences of each value.
Approach:
Count Occurrences: The first step is to traverse the linked list and count how many times each value appears. A hash table is ideal for this task because it provides constant-time (O(1)) average-case lookup, insertion, and deletion. We store the value as the key and the count as the value in the hash table.
Delete Duplicates: Next, we iterate through the linked list again. This time, we use a dummy node at the beginning of the list to simplify the handling of the head node. As we traverse:
pre
) to the current node.Return the Modified List: Finally, we return the next
pointer of the dummy node which now points to the head of the modified linked list.
Time Complexity Analysis:
Space Complexity Analysis:
Code Examples (Python, Java, C++, Go, TypeScript):
The provided code examples demonstrate the above approach in several programming languages. Each example follows these steps:
Example (Python):
from collections import Counter
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicatesUnsorted(self, head: ListNode) -> ListNode:
cnt = Counter()
cur = head
while cur:
cnt[cur.val] += 1
cur = cur.next
dummy = ListNode(0, head)
pre, cur = dummy, head
while cur:
if cnt[cur.val] > 1:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return dummy.next
The other language examples (Java, C++, Go, TypeScript) implement the same logic using their respective data structures and syntax. They all maintain the same O(n) time and O(n) space complexity.