Remove Duplicates from an Unsorted Linked list

Objective: Write a program to remove the duplicates from an unsorted linked list


Input Linked List : 1->2->2->4->3->3->2
Output : 1->2->4->3

Input: An unsorted linked list

Output: Linked list with no duplicates.


  • Create a Hash Map
  • Take two pointers, prevNode and CurrNode.
  • PrevNode will point to the head of the linked list and currNode will point to the

  • Now navigate through the linked list.
  • Check every node data is present in the Hash Map.
  • if yes then delete that node using prevNode and currNode.
  • If No, then insert that node data into the Hash Map.
  • Return the head of the list

Time Complexity : O(n)
Space Complexity : O(n)

Follow Up: If suppose addition buffer is not allowed then we have option but to check every node data against every other node data and if find duplicates, delete that node.
Time Complexity : O(n^2)

Complete Code for the Hash Table method:

import java.util.HashMap;
public class RD {
public Node removeDup(Node head){
HashMap<Integer, Integer> ht = new HashMap<Integer, Integer>();
return null;
Node currNode =;
Node prevNode = head;
Node temp; //keeping it so that last node would be eligible for garbage collection
ht.put(, 1);
int data =;
if(ht.containsKey(data)){ =;
temp= currNode;
currNode =; = null;
ht.put(data, 1);
prevNode = currNode;
currNode =;
} return head;
public void display(Node head){
Node n=head;
System.out.print("->" +;;
public static void main(String args[]){
Node n = new Node(2); = new Node(2); = new Node(2); = new Node(3); = new Node(4); = new Node(4); = new Node(2);
System.out.print("Original List : ");
RD rm = new RD();
System.out.print("\n Updated List: ");
Node x =rm.removeDup(n);
class Node{
int data;
Node next;
public Node(int data){ = data;
next = null;


Original List : ->1->2->2->3->4->4->2
Updated List: ->1->2->3->4