Python Program to Find Duplicate Elements in an Array.

Given an integer array arr[] of size n, the task is to write a Python program to find and print all duplicate elements present in the given array. Duplicate elements are those elements that appear more than once in the array. 

Example:

Input: num = [1, 2, 3, 4, 5, 2, 4, 6, 2, 7, 4, 2]
Output: [2, 4]
Explanation: 2 and 4 are present more than once in the array.

Input: num = [3, 2, 5, 1, 2, 3, 7, 6]
Output: [3, 2]
Explanation: 3 and 2 are present more than once in the array.

Python Program to Find List of Duplicate Elements of an Array.

In this approach, we are using a dictionary to store the number of occurrences of each element in the array. We iterate through each element of the array and check if it is already present in the dictionary. If the number is present, the code increases the count in the dictionary. If the number is not present then it is added to the dictionary with count 1. At the end, we add those elements to a new list whose count is greater than 1.

Python Code:
# Python code to find duplicate elements from array
def find_duplicates(nums):
    duplicates = []
    counts = {}

    for num in nums:
        if num in counts:
            counts[num] += 1
        else:
            counts[num] = 1

    for num, count in counts.items():
        if count > 1:
            duplicates.append(num)

    return duplicates


nums = [1, 2, 3, 4, 5, 2, 4, 6, 2, 7, 4, 2]
duplicates = find_duplicates(nums)
print(duplicates)
Output:
[2, 4]

Explanation:

The find_duplicates function uses a dictionary called counts to keep track of the frequency of each number in the array. It iterates through the array and updates the frequency count of each number in the dictionary. Then, it iterates through the dictionary and adds any number that occurs more than once to the duplicates list. Finally, it returns the duplicates list.

Time Complexity: The time complexity of the function is O(n), where n is the length of the input array. This is because it needs to iterate through the array twice: once to count the frequency of each number, and once to find the duplicates.

Space Complexity: The space complexity of the function is also O(n), where n is the length of the input array. This is because it needs to store the frequency count of each number in the dictionary, which in the worst case could be equal to the size of the input array.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS