Remove Duplicates From an Unsorted Linked List - Problem

Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.

Return the linked list after the deletions.

Note: A value that appears multiple times should have all its occurrences removed from the list.

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,3,2]
Output: [1,3]
💡 Note: Value 2 appears twice, so remove all nodes with value 2. Keep nodes with values 1 and 3 that appear only once.
Example 2 — Multiple Duplicates
$ Input: head = [2,1,1,2]
Output: []
💡 Note: Both values 1 and 2 appear twice, so all nodes are removed. The result is an empty list.
Example 3 — No Duplicates
$ Input: head = [1,2,3]
Output: [1,2,3]
💡 Note: All values appear exactly once, so no nodes are removed. The original list is returned.

Constraints

  • The number of nodes in the given list is in the range [1, 105]
  • 1 ≤ Node.val ≤ 105

Visualization

Tap to expand
Remove Duplicates From Unsorted Linked List INPUT Linked List Structure: 1 2 3 2 (duplicate) NULL Input Values: head = [1, 2, 3, 2] Value '2' appears 2 times Must remove ALL occurrences ALGORITHM STEPS 1 Count Frequencies Build hash map of counts HashMap: 1 : 1 2 : 2 3 : 1 2 Find Duplicates Mark values with count > 1 Duplicate: {2} 3 Traverse Again Skip nodes with dup values 4 Build Result Keep only unique nodes Time: O(n) | Space: O(n) Two passes through the list FINAL RESULT Cleaned Linked List: 1 3 NULL Removed nodes: 2 2 Output: [1, 3] OK - Success! All duplicates removed Key Insight: Use a Hash Map for two-pass approach: First pass counts frequency of each value. Second pass removes ALL nodes whose values appear more than once (not just the extra copies). This ensures O(n) time complexity with O(n) extra space for the frequency map. TutorialsPoint - Remove Duplicates From an Unsorted Linked List | Hash Approach
Asked in
Microsoft 25 Amazon 20 Google 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen