Remove duplicates from an array of small primes
Last Updated :
29 Feb, 2024
Given an array of primes arr[] such that the range of primes is small. Remove duplicates from the array.
Examples:
Input: arr[] = {3, 5, 7, 2, 2, 5, 7, 7}
Output: 2 3 5 7
Explanation: There are no duplicates among {2, 3, 5, 7}.
Input: arr[] = {3, 5, 7, 3, 3, 13, 5, 13, 29, 13}
Output: 3 5 7 13 29
Explanation: There are no duplicates among {3, 5, 7, 13, 29}
Source: Amazon Interview Question
Approach: This method discusses the naive approach which takes O(N2) time complexity.
So, the basic idea is to check for every element, whether it has occurred previously or not. Therefore, the approach involves keeping two loops, one to select the present element or index and the inner loop to check if the element has previously occurred or not.
Step-by-step algorithm:
- Start by running two loops.
- Pick all elements one by one.
- For every picked element, check if it has already occurred or not.
- If already seen, then ignore it, else add it to the array.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int removeDups(vector< int >& vect)
{
int res_ind = 1;
for ( int i = 1; i < vect.size(); i++) {
int j;
for (j = 0; j < i; j++)
if (vect[i] == vect[j])
break ;
if (j == i)
vect[res_ind++] = vect[i];
}
vect.erase(vect.begin() + res_ind, vect.end());
}
int main()
{
vector< int > vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Java
class GFG {
static int [] removeDups( int [] vect)
{
int res_ind = 1 ;
for ( int i = 1 ; i < vect.length; i++) {
int j;
for (j = 0 ; j < i; j++)
if (vect[i] == vect[j])
break ;
if (j == i)
vect[res_ind++] = vect[i];
}
int [] new_arr = new int [res_ind];
for ( int i = 0 ; i < res_ind; i++)
new_arr[i] = vect[i];
return new_arr;
}
public static void main(String[] args)
{
int [] vect = { 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 };
vect = removeDups(vect);
for ( int i = 0 ; i < vect.length; i++)
System.out.print(vect[i] + " " );
System.out.println();
}
}
|
C#
using System;
class GFG {
static int [] removeDups( int [] vect)
{
int res_ind = 1;
for ( int i = 1; i < vect.Length; i++) {
int j;
for (j = 0; j < i; j++)
if (vect[i] == vect[j])
break ;
if (j == i)
vect[res_ind++] = vect[i];
}
int [] new_arr = new int [res_ind];
for ( int i = 0; i < res_ind; i++)
new_arr[i] = vect[i];
return new_arr;
}
public static void Main(String[] args)
{
int [] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for ( int i = 0; i < vect.Length; i++)
Console.Write(vect[i] + " " );
Console.WriteLine();
}
}
|
Javascript
<script>
function removeDups(vect)
{
let res_ind = 1;
for (let i = 1; i < vect.length; i++) {
let j;
for (j = 0; j < i; j++)
if (vect[i] == vect[j])
break ;
if (j == i)
vect[res_ind++] = vect[i];
}
let new_arr = new Array(res_ind);
for (let i = 0; i < res_ind; i++)
new_arr[i] = vect[i];
return new_arr;
}
let vect=[3, 5, 7, 2, 2, 5, 7, 7];
vect = removeDups(vect);
for (let i = 0; i < vect.length; i++)
document.write(vect[i] + " " );
document.write( "<br>" );
</script>
|
Python3
def removeDups(vect):
res_ind = 1
for i in range ( 1 , len (vect)):
j = 0
while (j < i):
if (vect[i] = = vect[j]):
break
j + = 1
if (j = = i):
vect[res_ind] = vect[i]
res_ind + = 1
return vect[ 0 :res_ind]
vect = [ 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 ]
vect = removeDups(vect)
for i in range ( len (vect)):
print (vect[i], end = " " )
|
Complexity Analysis:
- Time Complexity: O(n2).
As two nested loops are used, so the time complexity becomes O(n2).
- Auxiliary Space: O(1).
Method 2: This method involves the technique of Sorting which takes O(n log n) time.
Approach:
In comparison to the previous approach, a better solution is to first sort the array and then remove all the adjacent elements which are similar, from the sorted array.
Step-by-step algorithm:
- First sort the array.
- The need for extra space can be cleverly avoided. Keeping two variables, first = 1 and i = 1.
- Traverse the array from the second element to the end.
- For every element, if that element is not equal to the previous element, then array[first++] = array[i], where i is the counter of a loop.
- So the length of the array with no duplicates is first, remove the rest elements.
Note: In CPP there are a few inbuilt functions like sort() to sort and unique() to remove adjacent duplicates. The unique() function puts all unique elements at the beginning and returns an iterator pointing to the first element after the unique element. The erase() function removes elements between two given iterators.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int removeDups(vector< int >& vect)
{
sort(vect.begin(), vect.end());
vect.erase(unique(vect.begin(), vect.end()),
vect.end());
}
int main()
{
vector< int > vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int [] removeDups( int [] vect)
{
Arrays.sort(vect);
int first = 1 ;
for ( int i = 1 ; i < vect.length; i++)
if (vect[i] != vect[i - 1 ])
vect[first++] = vect[i];
for ( int i = first; i < vect.length; i++)
vect[i] = Integer.MAX_VALUE;
return vect;
}
public static void main(String[] args)
{
int [] vect = { 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 };
vect = removeDups(vect);
for ( int i = 0 ; i < vect.length; i++) {
if (vect[i] == Integer.MAX_VALUE)
break ;
System.out.print(vect[i] + " " );
}
}
}
|
C#
using System;
class GFG
{
static int [] removeDups( int [] vect)
{
Array.Sort(vect);
int first = 1;
for ( int i = 1; i < vect.Length; i++)
if (vect[i] != vect[i - 1])
vect[first++] = vect[i];
for ( int i = first; i < vect.Length; i++)
vect[i] = int .MaxValue;
return vect;
}
public static void Main( params string [] args)
{
int [] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for ( int i = 0; i < vect.Length; i++)
{
if (vect[i] == int .MaxValue)
break ;
Console.Write(vect[i] + " " );
}
}
}
|
Javascript
<script>
function removeDups(vect) {
vect.sort((a, b) => a - b)
let first = 1;
for (let i = 1; i < vect.length; i++){
if (vect[i] != vect[i - 1])
vect[first++] = vect[i];
}
for (let i = first; i < vect.length; i++)
vect[i] = Number.MAX_SAFE_INTEGER;
return vect;
}
let vect = [ 3, 5, 7, 2, 2, 5, 7, 7 ];
removeDups(vect);
for (let i = 0; i < vect.length; i++) {
if (vect[i] == Number.MAX_SAFE_INTEGER)
break ;
document.write(vect[i] + " " );
}
</script>
|
Python3
import sys
def removeDups(vect):
vect.sort()
first = 1
for i in range ( 1 , len (vect)):
if (vect[i] ! = vect[i - 1 ]):
vect[first] = vect[i]
first + = 1
for i in range (first, len (vect)):
vect[i] = sys.maxsize
return vect
vect = [ 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 ]
vect = removeDups(vect)
for i in range ( len (vect)):
if (vect[i] = = sys.maxsize):
break
print (vect[i], end = " " )
|
Output:
Complexity Analysis:
- Time Complexity: O(n Log n).
For sorting the array O(n log n ) time complexity is required, and to remove adjacent elements O(n) time complexity is required.
- Auxiliary Space : O(1)
Since no extra space is required, the space complexity is constant.
Method 3: The method involves the technique of Hashing, which takes O(n) time.
Approach: The time complexity in this method can be reduced but space complexity will take a toll.
This involves the use of Hashing where the numbers are marked in a HashMap, so that if the number is again encountered, then erase it from the array.
Step-by-step algorithm:
- Use a hash set. HashSet stores only unique elements.
- It is known that if two of the same elements are put into a HashSet, the HashSet stores only one element (all the duplicate element vanishes)
- Traverse the array from start to end.
- For every element, insert the element into the HashSet
- Now Traverse the HashSet and put the elements in the HashSet in the array
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int removeDups(vector< int >& vect)
{
unordered_set< int > s(vect.begin(), vect.end());
vect.assign(s.begin(), s.end());
}
int main()
{
vector< int > vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static void removeDups(Vector<Integer> vect)
{
Set<Integer> set = new HashSet<Integer>(vect);
vect.clear();
vect.addAll(set);
}
public static void main(String[] args)
{
Integer arr[] = { 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 };
Vector<Integer> vect
= new Vector<Integer>(
Arrays.asList(arr));
removeDups(vect);
for ( int i = 0 ; i < vect.size(); i++) {
System.out.print(vect.get(i) + " " );
}
}
}
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static List< int > removeDups(List< int > vect)
{
HashSet< int > set = new HashSet< int >(vect);
vect.Clear();
vect = set .ToList();
return vect;
}
public static void Main(String[] args)
{
int [] arr = { 3, 5, 7, 2, 2, 5, 7, 7 };
List< int > vect = new List< int >(arr);
vect = removeDups(vect);
for ( int i = 0; i < vect.Count; i++) {
Console.Write(vect[i] + " " );
}
}
}
|
Javascript
<script>
function removeDups(vect)
{
letset = new Set(vect);
vect=[];
vect=Array.from(letset);
return vect;
}
let vect=[3, 5, 7, 2, 2, 5, 7, 7 ];
vect=removeDups(vect);
for (let i = 0; i < vect.length; i++) {
document.write(vect[i] + " " );
}
</script>
|
Python3
def removeDups():
global vect
s = set (vect)
vect = s
vect = [ 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 ]
removeDups()
for i in vect:
print (i, end = " " )
|
Complexity Analysis:
- Time Complexity: O(n).
Since a single traversal is needed to enter all the elements in the hashmap, the time complexity is O(n).
- Auxiliary Space: O(n).
For storing elements in HashSet or hashmap O(n) space complexity is needed.
Method 4: This focuses on small ranged values where the time complexity is O(n).
Approach:
This approach only works when the product of all distinct primes is fewer than 10^18 and all the numbers in the array should be prime. The property of primes of having no divisors except 1 or that number itself is used to arrive at the solution. As the array elements are removed from the array, they keep a value(product) which will contain the product of all distinct primes found previously in the array, so that if the element divides the product, they can be sure proved that the element has previously occurred in the array and hence the number will be rejected.
Step-by-step algorithm:
- Initially, keep a variable (p = 1).
- Traverse the array from start to end.
- While traversing, check whether p is divisible by the i-th element. If true, then erase that element.
- Else keep that element and update the product by multiplying that element with the product (p = p * arr[i])
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int removeDups(vector< int >& vect)
{
long long int prod = vect[0];
int res_ind = 1;
for ( int i = 1; i < vect.size(); i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
vect.erase(vect.begin() + res_ind, vect.end());
}
int main()
{
vector< int > vect{ 3, 5, 7, 2, 2, 5, 7, 7 };
removeDups(vect);
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int [] removeDups( int [] vect)
{
int prod = vect[ 0 ];
int res_ind = 1 ;
for ( int i = 1 ; i < vect.length; i++) {
if (prod % vect[i] != 0 ) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
return Arrays.copyOf(vect, res_ind);
}
public static void main(String[] args)
{
int [] vect = { 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 };
vect = removeDups(vect);
for ( int i = 0 ; i < vect.length; i++)
System.out.print(vect[i] + " " );
}
}
|
C#
using System;
class GFG {
static int [] removeDups( int [] vect)
{
int prod = vect[0];
int res_ind = 1;
for ( int i = 1; i < vect.Length; i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
}
}
int [] temp = new int [vect.Length - res_ind];
Array.Copy(vect, 0, temp, 0, temp.Length);
return temp;
}
public static void Main(String[] args)
{
int [] vect = { 3, 5, 7, 2, 2, 5, 7, 7 };
vect = removeDups(vect);
for ( int i = 0; i < vect.Length; i++)
Console.Write(vect[i] + " " );
}
}
|
Javascript
<script>
function removeDups(vect)
{
let prod = vect[0];
let res_ind = 1;
for (let i = 1; i < vect.length; i++) {
if (prod % vect[i] != 0) {
vect[res_ind++] = vect[i];
prod *= vect[i];
vect=vect.slice(0,res_ind + 2);
}
}
return vect;
}
let vect=[3, 5, 7, 2, 2, 5, 7, 7];
vect = removeDups(vect);
document.write(vect.join( " " ));
</script>
|
Python3
def remove_dups(vect):
prod = vect[ 0 ]
res_ind = 1
for i in range ( 1 , len (vect)):
if prod % vect[i] ! = 0 :
vect[res_ind] = vect[i]
res_ind + = 1
prod * = vect[i]
del vect[res_ind:]
vect = [ 3 , 5 , 7 , 2 , 2 , 5 , 7 , 7 ]
remove_dups(vect)
for num in vect:
print (num, end = " " )
|
Complexity Analysis:
- Time Complexity: O(n).
To traverse the array only once, the time required is O(n).
- Auxiliary Space: O(1).
One variable p is needed, so the space complexity is constant.
Note: This solution will not work if there are any composites in the array.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...