Friday, December 27, 2024
Google search engine
HomeLanguagesCount distinct elements in an array in Python

Count distinct elements in an array in Python

Given an unsorted array, count all distinct elements in it. Examples:

Input : arr[] = {10, 20, 20, 10, 30, 10} 
Output : 3

Input : arr[] = {10, 20, 20, 10, 20}
Output : 2

We have existing solution for this article. We can solve this problem in Python3 using Counter method. 

Approach#1: Using Set()

This ap roach defines a function count_distinct that takes an array as input and returns the count of distinct elements in the array using Python’s built-in set data structure. The set data structure is used to remove duplicates from the array and get only the distinct elements, and len function is used to get the count of those distinct elements. The program then calls this function with two different input arrays to demonstrate its functionality.

Algorithm

1. Create an empty set.
2. Traverse the given array, and add each element to the set.
3. The size of the set at the end will give the count of distinct elements.

Python3




def count_distinct(arr):
    distinct = set(arr)
    return len(distinct)
 
arr = [10, 20, 20, 10, 30, 10]
print(count_distinct(arr))
 
arr = [10, 20, 20, 10, 20]
print(count_distinct(arr))


Output

3
2

Time Complexity: O(n), where n is the number of elements in the array.
Auxiliary Space: O(n), where n is the number of elements in the array (to store the set).

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments