![]() |
VOOZH | about |
Given an integer array arr[], return the count of all the distinct elements in an array
Examples:
Input: arr[] = [2, 2, 3, 2]
Output: 2
Explanation: Distinct elements are [2, 3].
Input: arr[] = [12, 1, 14, 3, 16]
Output: 5
Explanation: Distinct elements are [12, 1, 14, 3, 16].
Input: arr[] = [1, 1, 1, 1]
Output: 1
Explanation: Only one distinct element [1].
Table of Content
The idea is to check whether each element has appeared before in the array. For every element, traverse all previous elements. If the current element is not found among the previous elements, increment the count of distinct elements.
res as 0. 0 to n - 1. arr[i], check whether it appears in the range 0 to i - 1. res. 5
Time Complexity: O(n^2)
Auxiliary Space: O(1)
The idea is to use a hash set to store all unique elements. Traverse the array and insert every element into an hash set. Since a set stores only distinct elements, the size of the set gives the count of distinct elements.
st. st. st.size(), which gives the count of distinct elements.5
Time Complexity: O(n)
Auxiliary Space: O(n)
One-Liner Code - O(n) Time and O(n) Space : The idea is to use the language's built-in Set data structure to remove duplicate elements directly. Since a set stores only unique elements, the number of distinct elements is equal to the size of the set.
5
Time Complexity: O(n)
Auxiliary Space: O(n)