C++ program for removing duplicate element in an array

Program to remove duplicates from an array

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

For example, consider the array

Example

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

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

remove-duplicates-array

Algorithm:-

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

C++ Code:-


     //c++ program for removing duplicate element in an array
     #include<iostream>
     #include<bits/stdc++.h>
     using namespace std;

    int remove_duplicate_elements(int arr[], int n)
    {

        if (n==0 || n==1)
            return n;

        int temp[n];

        int k = 0;
        int i;
        for (i=0i<n1i++)
            if (arr[i] != arr[i+1])
                temp[k++] = arr[i];
        temp[k++] = arr[n1];

        for (i=0i<j; i++)
            arr[i] = temp[i];

        return k;
    }

    void main(String[] args)
    {
        int n;
       
       cout<<\nEnter no. of elements you want in an array :”;
        cin>>n;
        int *a = new int[n+1];
       cout<<\nEnter all the elements”);

        for(int i = 0; i < n; i++)
        {
           cin>>a[i];
        }

        n = remove_duplicate_elements(a, n);
       cout<<\nArray after removing element :”;
       for(int i=0;i<=n; i++)
            cout<<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