VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-distinct-elements-in-an-array/

⇱ Count Distinct in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Distinct in an array

Last Updated : 7 Jun, 2026

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].

Using Two Loops - O(n^2) Time and O(1) Space

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.

  • Initialize a variable res as 0.
  • Traverse the array from 0 to n - 1.
  • For every element arr[i], check whether it appears in the range 0 to i - 1.
  • If the element has not appeared before, increment res.

Output
5

Time Complexity: O(n^2)
Auxiliary Space: O(1)

Using Hashing - O(n) Time and O(n) Space

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.

  • Create an hash set named st.
  • Traverse the array and insert every element into st.
  • Since a set stores only unique elements, duplicate values are automatically ignored.
  • Return st.size(), which gives the count of distinct elements.

Output
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.


Output
5

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: