Easy

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

### Complexity Analysis * **Time Complexity**: O(N^2) for naive approach or O(N log N) / O(N) with sorting or hashing. * **Space Complexity**: O(N) for hash set.



Thanks for feedback.



Read More....
Convert a sorted array into a binary search tree - recursive approach
Check if an array is a min heap
Minimum number of merge operation to make an array palindrom
Find the duplicate value in an array
Find the minimum element in a sorted and rotated array
Find the missing and repeated element in the given array