 Explore Edit Edit

# Program to remove duplicate elements in an array | FACE Prep

Published on 11 Mar 2020

Program to remove duplicate elements in an array (sorted and unsorted array cases) is discussed here. Given an array, all the duplicate elements of the array are removed.

For example, consider the array

## case 1:Remove duplicates from sorted array

Input: arr = {1, 2, 3, 4, 4}

Output: arr = {1, 2, 3, 4}

## case 2:Remove duplicates from unsorted array

Input: arr = {9, 2, 7, 4, 7}

Output: arr = {9, 2, 7, 4}

## Algorithm to remove duplicate elements in an array (sorted array)

• Input the number of elements of the array.
• Input the array elements.
• Repeat from i = 1 to n
• - if (arr[i] != arr[i+1])
• - temp[j++] = arr[i]
• - temp[j++] = arr[n-1]
• Repeat from i = 1 to j
• - arr[i] = temp[i]
• return j.

C
C++
Java
Python 3

Output
4
2
2
4
5
2 4 5

## Program to remove duplicate elements in an array (sorted array) using pointers

//Code using pointers
#include<stdio.h>
#include<stdlib.h>
int i,j;
int removed(int*,int);
int main()
{
int n,*a;
scanf(“%d”,&n);
a=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
scanf(“%d”,(a+i));
removed(a,n);
return 0;
}
int removed(int*a,int n)
{
int k;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;)
{
if(*(a+i)==*(a+j))
{
for(k=j;k<n;k++)
{
*(a+k)==*(a+k+1);
}
n–;
}
else
j++;
}
}
for(i=0;i<n;i++)
printf(“%d\n”,*(a+i));
return 0;
}


## Algorithm to remove duplicate elements in an array (unsorted array)

• Input the number of elements of the array.
• Input the array elements.
• Create a hashmap and store all the elements and their count.
• Print all the elements from the hashmap having count = 1.

## Program to remove duplicate elements in an array (unsorted array)

C++

Output
4
2
2
4
5
2 4 5

Recommended Programs  