Removing Duplicates elements from an array

remove duplicate elements from an array

Remove duplicate elements

Here we will learn about  how to Remove Duplicates elements from an array. Given an array, all the duplicate elements of the array are removed.

For example, consider the array

Example (sorted)

Input: arr = {1, 2, 3, 4, 4}

Output: arr = {1, 2, 3, 4}

In this article we will see two methods of how to remove duplicates elements from an array.

Method 1

Algorithm:

  • Input array elements separated by space
  • Reverse the array
  • Make a new array which have all the unique elements of input array.
  • Iterate through the new array and count the occurrence of each element. If input array have occurrence of number more than once. Remove from the input array
  • Reverse the input array
  • Print the input array

 

Python Code

print("Enter elements of an array separated by space")
a=list(map(int,input().split()))
a=a[::-1]
x=list(set(a))
for i in x:   
     m=a.count(i)
     for j in range(m-1):
        a.remove(i)
a=a[::-1]
print(a)

Output

Enter elements of an array separated by space
2 3 4 6 2
[2, 3, 4, 6]
Removing duplicate elements from an array in python

Method 2

 

Why we use set() for removing duplicates in an array

SET()- set takes iterable as input ( like lists, strings, arrays, ….)
Generally, sets do not allow duplicates.
So duplicate elements will be automatically removed by set property and this is why we are using sets to Remove duplicates from any iterables.

 

Algorithm :

  • Step1: Read array size
  • Step2: Read the input array
  • Step3: Use set() function to print array without duplicates

 

Python Code:

print("Enter elements of array separated by space")
a=map(int,input().split())
print("Unique element of an array are: ")
print(list(set(a)))

 

Output

Enter elements of array separated by space
1 2 3 1 2 4
Unique element of an array are: 
[1, 2, 3, 4]