Remove Duplicate Elements

Last updated: 29th Aug, 2020

              

Problem Statment

A sorted array **arr**of size **n** is given .
Print the new array **arr[]** with no duplicate element.
Constraints: 1 <= N <= 10^6 0 <= A <= 10^6

Input Format
[1,2,2,4,5,5,6]

Output Format
[1,2,4,5,6]

Approach:

1. remove_duplicate - function is declared with two arguments( arr : a array which  stores the elements , n: size of the array)
 the whole logic behind the program is that :
2. a loop will transverse through the array
3. if the current element is not equal to the next element of the array then , store the  element in a temporary list
4. store the temporary assigned list to the original array and print the unique  elements


Python Code

def remove_duplicate(n,arr):
# the length of array should be gretaer than 1
# else return n 
    if n <= 1: 
        return n 
#temporary variable to store unique elements of the array  
    temp = list(range(n))

#transverse through the array 
    y = 0; 
    for x in range(0, n-1):

#if the present element is not equal to the incremented element
#then store the present element in temporary list and
#increment the j value
        if arr[x] != arr[x+1]: 
            temp[y] = arr[x] 
            y += 1
#also store the last element,since it was not stored previously 
    temp[y] = arr[n-1] 
    y += 1
#change the original array with unique elements and return j
    for x in range(0, y): 
        arr[x] = temp[x] 
  
    return y 

#Drivers code

arr = [1,2,2,4,5,7]
n=len(arr)
print(remove_duplicate(n,arr))




C++ Code

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

  // Length of the array should be greater than 1
  // otherwise return the  array with length 1
  if(n<=1)
    return n;

  //  if the present element is not equal to the incremented element
  //  then store the present element in temporary list and
  //  increment the j value  
  int temp[] = new int[n];
  int y=0;
  for(int i = 0 ; i < n ; i++){
    if(arr[i] != arr[i+1])
        temp[y++] = arr[i];
  }

  // Also store the last element,since it was not stored previously
  temp[y++] = arr[n-1];

  // change the original array with unique elements and return j
  for(int i = 0 ; i < y ; i++)
      arr[i] = temp[i];

  return y;
}  


int main(){
  int arr[] = {1,2,3,3,3,6,6,7};
  int n=8;

  cout <<"Length of array  : "<< functionRemoveDuplicates(arr,n);
}