Signup/Sign In

Simple Program to remove Duplicate Element in an Array

In this tutorial, we will learn how to remove a duplicate element from an array. Before moving forward with the program, if you are not familiar with what is an Array please read this article: Array in C language.

remove duplicate from array

Remove duplicates from the sorted array:

Here we are implementing the program to remove a duplicate element from a sorted array. We will create a temporary array and copy elements from one array to another only in case when there is no next matching element.

Note: This program will work only for sorted array so while providing an input make sure that the given array is in a sorted array, otherwise it will give unexpected outputs.

#include <stdio.h>
int remove_duplicate(int arr[], int n)
{

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

  int temp[n];

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

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

  return j;
}

int main()
{
  int n;
  scanf("%d", &n);
  int arr[n];
  int i;
  for (i = 0; i < n; i++)
  {
    scanf("%d", &arr[i]);
  }
  printf("\nArray Before Removing Duplicates: ");
  for (i = 0; i < n; i++)
    printf("%d ", arr[i]);

  n = remove_duplicate(arr, n);

  printf("\nArray After Removing Duplicates: ");
  for (i = 0; i < n; i++)
    printf("%d ", arr[i]);

  return 0;
}


10
1 2 2 3 4 5 6 7 7 8

Array Before Removing Duplicates: 1 2 2 3 4 5 6 7 7 8
Array After Removing Duplicates: 1 2 3 4 5 6 7 8

Remove duplicates from the unsorted array:

In this program, we will take extra space to store a new array without the reputation of duplicate elements. We will run a nested loop first one is to copy the element from the array to temp array if that element is existing already in temp variable then we will break the inner loop and continue executing for remaining elements the same process.

#include <stdio.h>
int main()
{
  int n, count = 0;
  scanf("%d", &n);
  int arr[n], temp[n];
  for (int i = 0; i < n; i++)
  {
    scanf("%d", &arr[i]);
  }

  printf("\nArray Before Removing Duplicates: ");
  for (int i = 0; i < n; i++)
    printf("%d ", arr[i]);

  for (int i = 0; i < n; i++)
  {
    int j;
    for (j = 0; j < count; j++)
    {
      if (arr[i] == temp[j])
        break;
    }
    if (j == count)
    {
      temp[count] = arr[i];
      count++;
    }
  }

  printf("\nArray After  Removing Duplicates: ");
  for (int i = 0; i < count; i++)
    printf("%d ", temp[i]);

  return 0;
}


10
1 2 2 3 4 5 6 7 7 8

Array Before Removing Duplicates: 1 2 2 3 4 5 6 7 7 8
Array After Removing Duplicates: 1 2 3 4 5 6 7 8

 

Suggested Tutorials: