Remove duplicates from a sorted array

Given a sorted array and remove duplicates from array. Simple C program to remove duplicates from array.

C Program:

#include<stdio.h>
 
/* Function to remove duplicates from sorted array */ 
int  RemoveDuplicate(int arr[],int size)
{
 int i,j=0;
 
 for(i=1,j=0;i<size;i++)
 {
  if(arr[i]!=arr[j])
  {
   j++;
   arr[j]=arr[i];
 
  }
 }
 //size = j+1
 return j+1;
}
 /* Function to print array */
void PrintArray(int arr[], int size)
{
 int i;
 
 for(i=0;i<size;i++)
 {
  printf("%d ",arr[i]);
 }
 
}
int main()
{
 int arr[]={1,1,4,5,7,7,8,12,12,12,20};
 
 /* Find size of array using sizeof function */
 int size = sizeof(arr)/sizeof(arr[0]);
 
 /* Update size of array */
 size = RemoveDuplicate(arr,size);
 
 PrintArray(arr,size);
 
 return 0;
}

Time complexity of this program is O(n).

Related: Remove duplicates from unsorted array

Popular posts from this blog