Arrays: Program to remove duplicates from an unsorted array



Given an unsorted array containing duplicate elements, we want to remove the duplicate elements from the array

 
Approach
  1. The idea is to traverse the array and inspect each element
  2. Since the array is unsorted, we need a way to keep track of elements that we have previously seen.
  3. We will use a hashmap to store each element while traversal.
  4. While traversing elements, if the element already exists in hashmap, we know this is a duplicate so will skip it
  5. Finally the hashmap will consist of all unique elements and we will get our result
 
Complexity

Time Complexity : O(n), where n is the number of elements in the array
Space Complexity: O(n), since we are using a hashmap

 
Java Code
import java.util.*;

    class RemoveDuplicateFromUnsortedArray{
        static void removeDuplicateFromUnsortedArray(int[] arr, int n){
    
            HashMap uniqueElements = new HashMap<>();
     
            for (int i = 0; i < n; ++i){
                if(!uniqueElements.containsKey(arr[i])){
                    uniqueElements.put(arr[i], 1);
                }
            }
    
            System.out.println("Array elements without duplicates: ");
            for(Map.Entry entry : uniqueElements.entrySet()) {
                System.out.print(entry.getKey() + " ");
            }
        }
    
        public static void main(String[] args){
            int[] unsortedArray = {7,4,6,4,9,2,7,6,5,3,7,4};
            
            System.out.println("Array elements with duplicates: ");
            for(int element: unsortedArray){
                System.out.print(element + " ");
            }
    
            System.out.println();
            
            int n = unsortedArray.length;
            removeDuplicateFromUnsortedArray(unsortedArray, n);
        }
    
 }
 
Output

Array elements with duplicates:
7 4 6 4 9 2 7 6 5 3 7 4
Array elements without duplicates:
2 3 4 5 6 7 9



Thanks for feedback.



Read More....
Check if an array is a min heap
Convert a sorted array into a binary search tree - recursive approach
Print the elements of an array
Find the kth largest element in the array
Find the kth smallest element in the array
Merge two sorted arrays