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))