Remove duplicates from unsorted array using Set data structure
Last Updated :
11 Aug, 2022
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.
Input: arr[] = { 3, 3, 4, 1, 1}
Output: 3 4 1
Approach:
- Take a Set
- Insert all array element in the Set. Set does not allow duplicates and sets like LinkedHashSet maintains the order of insertion so it will remove duplicates and elements will be printed in the same order in which it is inserted.
- Convert the formed set into array.
- Print elements of Set.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void removeDuplicates( int arr[], int n)
{
unordered_set< int > s;
for ( int i = 0; i < n; i++)
s.insert(arr[i]);
cout << "[ " ;
for ( auto x : s)
cout << x << " " ;
cout << "]" ;
}
int main()
{
int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
removeDuplicates(arr, n);
}
|
Java
import java.util.*;
class GFG {
public static void removeDuplicates( int [] arr)
{
LinkedHashSet<Integer> set
= new LinkedHashSet<Integer>();
for ( int i = 0 ; i < arr.length; i++)
set.add(arr[i]);
System.out.print(set);
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 5 , 1 , 7 , 2 , 4 , 2 };
removeDuplicates(arr);
}
}
|
Python3
def removeDulipcates(arr):
return list ( set (arr))
arr = [ 1 , 2 , 5 , 1 , 7 , 2 , 4 , 2 ]
print (removeDulipcates(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static void removeDuplicates( int [] arr)
{
HashSet< int > set = new HashSet< int >();
for ( int i = 0; i < arr.Length; i++)
set .Add(arr[i]);
foreach ( int item in set ) Console.Write(item + ", " );
}
public static void Main(String[] args)
{
int [] arr = { 1, 2, 5, 1, 7, 2, 4, 2 };
removeDuplicates(arr);
}
}
|
Javascript
<script>
function removeDuplicates(arr)
{
let set = new Set();
for (let i = 0; i < arr.length; i++)
set.add(arr[i]);
document.write( "[" + Array.from(set).join( ", " ) + "]" );
}
let arr = [ 1, 2, 5, 1, 7, 2, 4, 2 ];
removeDuplicates(arr);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N) as using unordered_set
Share your thoughts in the comments
Please Login to comment...