Problem: Given an array, delete all duplicate elements from it in the C programming language.

Remove duplicates from array

The idea is to divide the array into unique and duplicate partitions by finding and shifting all duplicates to one side.

For this, we will compare each element of the array with all other elements that exist after its index value and if a match is found we will simply swap the duplicate element with the last element of the array (i.e. array [size-1]).

Shift duplicates to the right

Every time we do the swapping, we decrement the value of size by 1 to exclude the count of the duplicate values.

Here is the implementation of the approach in C:

#include <stdio.h>
 
int main()
{
  int size, temp;

  printf("Enter size of array \n");
  scanf("%d",&size);

  int array[size];

  //Take input in the array
  printf("Enter %d element in the array \n",size);
  for(int i=0; i<size; i++){
    scanf("%d",&array[i]);
  }

  //Output original array
  printf("Original Array \n");
  for(int i=0; i<size; i++){
    printf("%d ",array[i]);
  }
  printf("\n");

 
  //iterate through each element
  for(int i=0; i<size-1; i++){
    
    //compare it with all elements on right
    for(int j=i+1; j<size; j++){
      if(array[i] == array[j]){
        /*
          *shift duplicate element to the last,
          *by swapping it with array[size]
        */
        temp = array[j];
        array[j] = array[size-1];
        array[size-1] = temp;

        //reduce size of the array
        size--; 
      }
    }
  }

  //Output Final array
  printf("Filtered Array \n");
  for(int i=0; i<size; i++){
    printf("%d ",array[i]);
  }

  return 0;
}

Output:

Enter size of array
6
Enter 6 element in the array
1 3 2 2 4 3
Original Array
1 3 2 2 4 3
Filtered Array
1 3 2 4


Overall in the above program, we are basically transferring all duplicates to the right of the array and only printing the left part of it which has no duplicates.

In this programming example, we learned to remove duplicates elements from an array using the C programming language.

Leave a Reply