Write code to remove duplicates in a sorted array

In this simple C program, we change the original array and also send the new size of the array back to the caller.

Method 1


// Function to remove the duplicates
 int removeDuplicates(int a[], int array_size)
 {
   int i, j;

   j = 0;

   // Print old array...
   printf("\n\nOLD : ");
   for(i = 0; i < array_size; i++)
   {
      printf("[%d] ", a[i]);
   }

   // Remove the duplicates ...
   for (i = 1; i < array_size; i++)
   {
     if (a[i] != a[j])
     {
       j++;
       a[j] = a[i]; // Move it to the front
     }
   }

   // The new array size..
   array_size = (j + 1);

   // Print new array...
   printf("\nNEW : ");
   for(i = 0; i< array_size; i++)
   {
      printf("[%d] ", a[i]);
   }
   printf("\n\n");

   // Return the new size...
   return(j + 1);
 }

And here is the output…


OLD : [1] [1] [2] [3] [5] [6] [6] [7] [10] [25] [100] [123] [123]
NEW : [1] [2] [3] [5] [6] [7] [10] [25] [100] [123]

Method 2

If we dont want to change the input array and just want to print the array without any duplicates, the solution is very simple. Check out the removeDuplicatesNoModify() function in the program below. It keeps a track of the most recently seen number and does not print any duplicates of it when traversing the sorted array.


void removeDuplicatesNoModify(int array[], int array_size)

{
    int i, last_seen_unique;

    if(array_size <= 1){return;}

    last_seen_unique = array[0];

    printf("\n\nOld : ", array_size);

    for(i = 0; i < array_size; i++)
    {
      printf("[%2d] ", array[i]);
    }

    printf("\nNew : ", array_size);

    printf("[%2d] ", array[0]);
    for(i=1; i < array_size; i++)
    {
        if(array[i]!=last_seen_unique)
        {
           printf("[%2d] ", array[i]);
           last_seen_unique = array[i];
        }
    }

    printf("\n");
 }

One Thought on “Write code to remove duplicates in a sorted array

  1. vignesh on January 21, 2016 at 4:42 pm said:

    please I need compiler in this site

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation