Remove duplicates from unsorted array using Map data structure
Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence.
Examples:
Input : arr[] = { 1, 2, 5, 1, 7, 2, 4, 2}
Output : 1 2 5 7 4
Explanation : {1, 2} appear more than one time.
Approach :
- Take a hash map, which will store all the elements which have appeared before.
- Traverse the array.
- Check if the element is present in the hash map.
- If yes, continue traversing the array.
- Else Print the element.
Implementation:
C++
#include "iostream"
#include "unordered_map"
using namespace std;
void removeDups( int arr[], int n)
{
unordered_map< int , bool > mp;
for ( int i = 0; i < n; ++i) {
if (mp.find(arr[i]) == mp.end()) {
cout << arr[i] << " " ;
}
mp[arr[i]] = true ;
}
}
int main( int argc, char const * argv[])
{
int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
removeDups(arr, n);
return 0;
}
|
Java
import java.util.HashMap;
class GFG
{
static void removeDups( int [] arr, int n)
{
HashMap<Integer,
Boolean> mp = new HashMap<>();
for ( int i = 0 ; i < n; ++i)
{
if (mp.get(arr[i]) == null )
System.out.print(arr[i] + " " );
mp.put(arr[i], true );
}
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 5 , 1 , 7 , 2 , 4 , 2 };
int n = arr.length;
removeDups(arr, n);
}
}
|
Python3
def removeDups(arr, n):
mp = {i : 0 for i in arr}
for i in range (n):
if mp[arr[i]] = = 0 :
print (arr[i], end = " " )
mp[arr[i]] = 1
arr = [ 1 , 2 , 5 , 1 , 7 , 2 , 4 , 2 ]
n = len (arr)
removeDups(arr,n)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void removeDups( int [] arr, int n)
{
Dictionary< int ,
Boolean> mp = new Dictionary< int , Boolean>();
for ( int i = 0; i < n; ++i)
{
if (!mp.ContainsKey(arr[i]))
Console.Write(arr[i] + " " );
mp[arr[i]] = true ;
}
}
public static void Main(String[] args)
{
int [] arr = { 1, 2, 5, 1, 7, 2, 4, 2 };
int n = arr.Length;
removeDups(arr, n);
}
}
|
Javascript
<script>
function removeDups(arr,n)
{
let mp = new Map();
for (let i = 0; i < n; ++i)
{
if (mp.get(arr[i]) == null )
document.write(arr[i] + " " );
mp.set(arr[i], true );
}
}
let arr=[1, 2, 5, 1, 7, 2, 4, 2 ];
let n = arr.length;
removeDups(arr, n);
</script>
|
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Last Updated :
07 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...