Write a program to Delete Duplicate Elements from an Array


This Java program removes duplicate elements from an integer array. It uses the following approach:

  • If the array length is zero or one, then there are no duplicates to remove, so the method returns the original length.
  • A new temporary array is created with the same length as the original array.
  • The elements of the original array are scanned, and each element is copied to the temporary array if it is not equal to the next element.
  • The last element of the original array is always copied to the temporary array, because it is never compared to another element.
  • The elements of the temporary array are then copied back to the original array, and the new length of the array is returned.

The main method initializes an array with some duplicate elements, calls the removeduplicates method, and then prints out the resulting array without duplicates.

Source Code

class Delete_Duplicate
{
	public static void main(String[] args)
	{
		int a[] = { 10, 10, 20, 20, 30 };
		int n = a.length;
		System.out.println("After Remove Duplicate Array Element..");
		n = removeduplicates(a, n);
		for (int i = 0; i < n; i++)
			System.out.print(a[i] + " ");
    }
	public static int removeduplicates(int a[], int n)
	{
		if (n == 0 || n == 1)
		{
			return n;
		}
		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];
		for (int i = 0; i < j; i++)
		{
			a[i] = temp[i];
		}
 
		return j;
	}
}
 

Output

After Remove Duplicate Array Element..
10 20 30

Example Programs