# Java program for removing duplicate element in an array

## Remove Duplicates elements

Here is a program to remove duplicate elements in an array  is discussed here. Given an array, all the duplicate elements of the array are removed.

For example, consider the array

#### Example (sorted)

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

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

## Algorithm

• 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.

## Java Code

```import java.util.*;
public class Main{
public static int removeduplicates(int a[], int n)
{
if (n == 0 || n == 1) {
return n;
}

// creating another array for only storing
// the unique elements
int[] temp = new int[n];
int j = 0;

for (int i = 0; i < n - 1; i++) {
if (a[i] != a[i + 1]) {
temp[j++] = a[i];
}
}

temp[j++] = a[n - 1];

// Changing the original array
for (int i = 0; i < j; i++) {
a[i] = temp[i];
}

return j;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
int n;
n = s.nextInt();

int a[] = new int[n];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}

n = removeduplicates(a, n);

// Printing The array elements
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}

}
```

## Output

```Enter size of an array
6
Enter elements in an array
1
2
3
3
4
5
After removing duplicate elements 1,2,3,4,5```

### 2 comments on “Java program for removing duplicate element in an array”

• SRT

#include
int main()
{
int count, i, j, n;
int arr[100];
scanf(“%d”, &n);
for(i = 0; i<n; i++)
{
scanf("%d", &arr[i]);
}
for(i = 0; i<n; i++)
{ //finding non repeating character//
count = 0;
for(j = 0; j<n; j++)
{
if(arr[i] == arr[j])
{
if(i!=j)
{
count++;
}
}
}

if(count == 0)
{
printf(" %d", arr[i]); // printing above code//
}
// finding repeating character //
count = 0;
for(j = i + 1; j<n; j++)
{
if(arr[i] == arr[j])
{
if(i!=j)
{
count++;
}
}
}

if(count == 1)
{
printf(" %d", arr[i]); // printing above code//
// with space given it will print all code in one line//
}

}
return 0;
}

• Ajay

#include
using namespace std;
int main()
{
int a[50],n,temp;
int i,j;
cout<<" enter size "<>n;
cout<<" \n enter elements \n";
for(i=0;i>a[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;ja[j])
{
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
int temp2[50];
int k=0;
for(i=0;i<n-1;i++)
{
if(a[i]!= a[i+1])
{
temp2[k++]=a[i];
}
}
temp2[k++]=a[n-1];
cout<<"duplicate removed array =";
for(i=0;i<k;i++)
{
cout<<" "<<temp2[i];
}
return 0;
}