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

Try It Yourself
redirect icon

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.
C++
#include <iostream>
using namespace std;

int countDistinct(vector<int> &arr)
{

    int n = arr.size();

    if (n == 0)
    {
        return 0;
    }

    // Stores count of distinct elements
    int res = 1;

    // Pick all elements one by one
    for (int i = 1; i < n; i++)
    {

        int j;

        // Check whether current element
        // appeared before or not
        for (j = 0; j < i; j++)
        {
            if (arr[i] == arr[j])
            {
                break;
            }
        }

        // If current element is seen
        // for the first time
        if (i == j)
        {
            res++;
        }
    }

    return res;
}

// Driver Code
int main()
{

    vector<int> arr = {12, 10, 9, 45, 2, 10, 10, 45};

    cout << countDistinct(arr);

    return 0;
}
C
#include <stdio.h>

int countDistinct(int arr[], int n)
{
    if (n == 0)
    {
        return 0;
    }

    // Stores count of distinct elements
    int res = 1;

    // Pick all elements one by one
    for (int i = 1; i < n; i++)
    {
        int j;

        // Check whether current element
        // appeared before or not
        for (j = 0; j < i; j++)
        {
            if (arr[i] == arr[j])
            {
                break;
            }
        }

        // If current element is seen
        // for the first time
        if (i == j)
        {
            res++;
        }
    }

    return res;
}

// Driver Code
int main()
{
    int arr[] = {12, 10, 9, 45, 2, 10, 10, 45};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("%d", countDistinct(arr, n));

    return 0;
}
Java
public class GfG {
    public static int countDistinct(int[] arr)
    {
        int n = arr.length;

        if (n == 0) {
            return 0;
        }

        // Stores count of distinct elements
        int res = 1;

        // Pick all elements one by one
        for (int i = 1; i < n; i++) {
            int j;

            // Check whether current element
            // appeared before or not
            for (j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    break;
                }
            }

            // If current element is seen
            // for the first time
            if (i == j) {
                res++;
            }
        }

        return res;
    }

    public static void main(String[] args)
    {
        int[] arr = { 12, 10, 9, 45, 2, 10, 10, 45 };

        System.out.println(countDistinct(arr));
    }
}
Python
def countDistinct(arr):
    n = len(arr)

    if n == 0:
        return 0

    # Stores count of distinct elements
    res = 1

    # Pick all elements one by one
    for i in range(1, n):
        j = 0
        # Check whether current element
        # appeared before or not
        while j < i:
            if arr[i] == arr[j]:
                break
            j += 1
        # If current element is seen
        # for the first time
        if i == j:
            res += 1
    return res


# Driver Code
if __name__ == "__main__":

    arr = [12, 10, 9, 45, 2, 10, 10, 45]

    print(countDistinct(arr))
C#
using System;

public class GfG {
    public static int countDistinct(int[] arr)
    {
        int n = arr.Length;

        if (n == 0) {
            return 0;
        }

        // Stores count of distinct elements
        int res = 1;

        // Pick all elements one by one
        for (int i = 1; i < n; i++) {
            int j;

            // Check whether current element
            // appeared before or not
            for (j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    break;
                }
            }

            // If current element is seen
            // for the first time
            if (i == j) {
                res++;
            }
        }

        return res;
    }

    public static void Main()
    {
        int[] arr = { 12, 10, 9, 45, 2, 10, 10, 45 };

        Console.WriteLine(countDistinct(arr));
    }
}
JavaScript
function countDistinct(arr) {
    let n = arr.length;

    if (n === 0) {
        return 0;
    }

    // Stores count of distinct elements
    let res = 1;

    // Pick all elements one by one
    for (let i = 1; i < n; i++) {
        let j;

        // Check whether current element
        // appeared before or not
        for (j = 0; j < i; j++) {
            if (arr[i] === arr[j]) {
                break;
            }
        }

        // If current element is seen
        // for the first time
        if (i === j) {
            res++;
        }
    }

    return res;
}

// Driver Code
let arr = [12, 10, 9, 45, 2, 10, 10, 45];

console.log(countDistinct(arr));

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.
C++
#include <bits/stdc++.h>
using namespace std;

int countDistinct(vector<int> &arr)
{

    // Stores all unique elements
    unordered_set<int> st;

    // Insert every element into the set
    for (int x : arr)
    {
        st.insert(x);
    }

    // Size of set gives the count
    // of distinct elements
    return st.size();
}

// Driver Code
int main()
{

    vector<int> arr = {12, 1, 14, 3, 16};

    cout << countDistinct(arr);

    return 0;
}
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// Function to check if an element exists in the array
bool exists(int arr[], int size, int element)
{
    for (int i = 0; i < size; i++)
    {
        if (arr[i] == element)
        {
            return true;
        }
    }
    return false;
}

int countDistinct(int arr[], int n)
{
    int distinctCount = 0;
    int *distinctElements = (int *)malloc(n * sizeof(int));

    for (int i = 0; i < n; i++)
    {
        if (!exists(distinctElements, distinctCount, arr[i]))
        {
            distinctElements[distinctCount++] = arr[i];
        }
    }

    free(distinctElements);
    return distinctCount;
}

int main()
{
    int arr[] = {12, 1, 14, 3, 16};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("%d", countDistinct(arr, n));

    return 0;
}
Java
import java.util.HashSet;

public class GfG {
    public static int countDistinct(int[] arr)
    {
        // Stores all unique elements
        HashSet<Integer> st = new HashSet<>();

        // Insert every element into the set
        for (int x : arr) {
            st.add(x);
        }

        // Size of set gives the count
        // of distinct elements
        return st.size();
    }

    public static void main(String[] args)
    {
        int[] arr = { 12, 1, 14, 3, 16 };
        System.out.println(countDistinct(arr));
    }
}
Python
def countDistinct(arr):
    # Stores all unique elements
    st = set()

    # Insert every element into the set
    for x in arr:
        st.add(x)

    # Size of set gives the count
    # of distinct elements
    return len(st)


# Driver Code
if __name__ == "__main__":

    arr = [12, 1, 14, 3, 16]

    print(countDistinct(arr))
C#
using System;
using System.Collections.Generic;

public class GfG {
    public static int countDistinct(int[] arr)
    {
        // Stores all unique elements
        HashSet<int> st = new HashSet<int>();

        // Insert every element into the set
        foreach(int x in arr) { st.Add(x); }

        // Size of set gives the count
        // of distinct elements
        return st.Count;
    }

    public static void Main()
    {
        int[] arr = { 12, 1, 14, 3, 16 };
        Console.WriteLine(countDistinct(arr));
    }
}
JavaScript
function countDistinct(arr)
{
    // Stores all unique elements
    let st = new Set();

    // Insert every element into the set
    for (let x of arr) {
        st.add(x);
    }

    // Size of set gives the count
    // of distinct elements
    return st.size;
}

// Driver Code
let arr = [ 12, 1, 14, 3, 16 ];
console.log(countDistinct(arr));

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.

Python
arr = [12, 10, 9, 45, 2, 10, 10, 45]

print(len(set(arr)))
JavaScript
function main()
{

    let arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ];

    console.log(new Set(arr).size);
}

main();

Output
5

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

Comment