Python program that uses a dictionary to print the duplicate elements of an array:

Created with Sketch.

Python program that uses a dictionary to print the duplicate elements of an array:

def print_duplicates(arr):
    freq = {}
    for i in arr:
        if i in freq:
            freq[i] += 1
        else:
            freq[i] = 1
    for key, value in freq.items():
        if value > 1:
            print(key)

# Example usage
arr = [1, 2, 3, 2, 4, 1, 5, 2, 1]
print_duplicates(arr)

The function print_duplicates(arr) takes an array as an argument. It first creates an empty dictionary freq. Then, it uses a for loop to iterate over the array, and for each element, it checks if the element already exists in the dictionary freq, if it does, it increases the value of the element by 1, otherwise it initializes the element with a value of 1. After that, it uses another for loop to iterate over the items in the dictionary, and for each item, it checks if the value of the item is greater than 1, if it is, it prints the key (element) of the item, which is a duplicate.

The example usage creates an array and calls the print_duplicates() function to find the duplicate elements in the array, and then it prints the duplicate elements of the array.

You could also use collections.Counter() method along with a loop to find the duplicate elements in an array, this method

Leave a Reply

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