Python Program to Find duplicates in an Array

 

 

Duplicate Elements: Find duplicates in an array

This program demonstrates how to find duplicate elements in an array using Python. The algorithm iterates through the array and uses a set to track seen elements. If an element is found in the set, it is identified as a duplicate.

Python Program

def find_duplicates(arr):
    """
    Finds and returns duplicate elements in the given array.

    :param arr: The array to check for duplicates.
    :return: A list of duplicate elements.
    """
    seen = set()
    duplicates = set()

    for element in arr:
        if element in seen:
            duplicates.add(element)
        else:
            seen.add(element)

    return list(duplicates)

if __name__ == "__main__":
    array = [1, 2, 3, 4, 5, 6, 7, 2, 3, 8, 9, 10, 10]
    duplicates = find_duplicates(array)

    if not duplicates:
        print("No duplicates found.")
    else:
        print("Duplicate elements:", duplicates)

Explanation

The program includes the following components:

  • def find_duplicates(arr):: Defines a function that takes a list of integers as input and returns a list of duplicate elements.
  • seen = set(): Initializes a set to keep track of elements that have been encountered in the array.
  • duplicates = set(): Initializes a set to store duplicate elements.
  • for element in arr:: Iterates through each element in the array.
  • if element in seen:: Checks if the element is already in the seen set. If it is, the element is a duplicate.
  • duplicates.add(element): Adds the duplicate element to the duplicates set.
  • return list(duplicates): Converts the set of duplicates to a list and returns it.
  • if __name__ == "__main__":: The main block that initializes an array and calls the find_duplicates function.
  • print("Duplicate elements:", duplicates): Prints the duplicate elements.

The example array array = [1, 2, 3, 4, 5, 6, 7, 2, 3, 8, 9, 10, 10] contains the duplicates 2, 3, and 10. When the find_duplicates function is called, it will print:

No duplicates found.
Duplicate elements: [2, 3, 10]

 

Explanation
Python Program: The provided Python program utilizes sets to identify duplicate elements in an array. The find_duplicates function iterates through the array, using a set called seen to track elements that have been encountered. If an element is already in the seen set, it is added to a set called duplicates.

Output: The output of the program will list all the duplicate elements found in the array.

Leave a Reply

Your email address will not be published. Required fields are marked *