Find duplicate in an array of N+1 Integers in Python

Duplicates element in array of n+1 integer in python

Duplicate elements in an array

In this article we will see a python program to find Duplicate elements in an array. Duplicates elements are those whose existence in array is more than once. We are required to find those duplicates element in array.

Let us consider an example for better understanding.

  • Array= [1,2,3,1,5,2]
  • Duplicate element= 1,2

Algorithm

  • Step 1: Take array
  • Step 2: Print the array
  • Step 3: Call the function find

Algorithm for function find

  • Step 1: Declare an empty array with name duplicate_element_array
  • Step 2: Iterate on the elements of array 

                     1.  Count the number of occurrence in of that elements in array and check if it greater than one.

                     2.  If above(1) is true, then check if that element is not in duplicate_element_array. 

                     3.  If (1) and (2) is true then, append that element in duplicate_element_array.

  • Step 3: Print elements of duplicate_element_array.
python program to find duplicates element in array of n+1 integer

Python Code

Run
def find(array):
    # Declare an array which will store all the duplicate elements
    duplicate_element_array = []

    # Iterate on the elements of array to find duplicate elements
    for i in array:
        if array.count(i) > 1 and i not in duplicate_element_array:
            duplicate_element_array.append(i)

    # Print all duplicate elements
    print("Duplicate element in an array : ", end="")
    for i in sorted(duplicate_element_array):
        print(i, end=" ")


# declare array
array = [-1, 8, 1, 8, -1, 5, 1, -3]

# print(array)
print("Array= ", array)
find(array)

Output

Array= [-1, 8, 1, 8, -1, 5, 1, -3]
Duplicate element in an array : -1 1 8

Comments