Java program to count distinct element in an array

Count distinct element in an array in Java

In this section, we will learn, how to Count distinct element in an array in java language.

Given an integer array, we have to print all the distinct element of the input array. input array may contain duplicate elements, we have to print the count of distinct elements.

java Program to Counting distinct elements

Methods Discussed are :

  • Method 1 : Using Two loops
  • Method 2 : Using hash Map

Let’s discuss each method one by one,

Method 1 :

In this method we will count the frequency of each elements using two for loops.

  • To check the status of visited elements create a array of size n and a variable say count_dis=0 to count the distinct element.
  • Run a loop from index 0 to n and check if (visited[i]==1) then skip that element.
  • Run a loop from index i+1 to n
  • Check if(arr[i]==arr[j]), then set visited[j]=1.
  • After complete iteration of inner for loop and increment the value of count_dis
  • At last print the value count_dis

Time and Space Complexity :

  • Time Complexity : O(n2)
  • Space Complexity : O(n)

Method 1 : Code in Java

Run
import java.util.Arrays;

class Main
{
   public static void countFreq(int arr[], int n)
   {
         boolean visited[] = new boolean[n];
         Arrays.fill(visited, false);
         int count_dis=0;
         // Traverse through array elements and
         // count frequencies
         for (int i = 0; i < n; i++) {

            // Skip this element if already processed
            if (visited[i] == true)
             continue;

           
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                   visited[j] = true;
                   
                }
            }
            count_dis = count_dis+1;
   }
   System.out.println(count_dis);
  }

   // Driver code
   public static void main(String []args)
   {
      int arr[] = new int[]{10, 30, 40, 20, 10, 20, 50, 10};
      int n = arr.length;
      countFreq(arr, n);
   }
}

Output

5

Method 2 :

In this method we will count use hash-map to count the frequency of each elements.

  • Declare a hash map and a variable count_dis=0.
  • Start iterating over the entire array
  • If element is present in map, then increase the value of frequency by 1.
  • Otherwise, insert that element in map.
  • After complete iteration over array, print the size of map.

Time and Space Complexity :

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

Method 2 : Code in Java

Run
import java.util.*;
import java.util.Arrays;

class Main
{
   static void countFreq(int arr[], int n)
   {
      Map<Integer, Integer> mp = new HashMap<>();
      int count_dis=0;
      // Traverse through array elements and
      // count frequencies
      for (int i = 0; i < n; i++)
      {
         if (mp.containsKey(arr[i]))
         {
           mp.put(arr[i], mp.get(arr[i]) + 1);
         }
         else
         {
           mp.put(arr[i], 1);
         }
     }
     
     System.out.println(mp.size());
  }
  // Driver code
  public static void main(String []args)
  {
       int arr[] = new int[]{10, 40, 50, 20, 10, 20, 30, 10};
       int n = arr.length;
       countFreq(arr, n);
  }
}

Output

5

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

12 comments on “Java program to count distinct element in an array”


  • Deepikala V

    import java.util.*;
    class Countofdistinct{
    public static void main(String[] args)
    {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int arr[]=new int[n];
    for(int i=0;i<n;i++)
    arr[i]=sc.nextInt();
    getDistinct(arr,n);
    }
    static void getDistinct(int[] arr,int n)
    {
    int c=0;
    for(int i=0;i<n;i++)
    {
    boolean distinct=true;
    for(int j=i+1;j<n;j++)
    {
    if(arr[i]==arr[j]){
    distinct=false;
    break;}
    }
    if(distinct)
    c++;
    }
    System.out.println(c);
    }}


  • Pulivendula

    import java.util.*;
    public class Main
    {
    public static void main(String[] args)
    {
    int a[]={10, 30, 40, 20, 10, 20, 50, 10};
    TreeSet h= new TreeSet();
    for(int i:a)
    {
    h.add(i);
    }
    int c=h.size();
    System.out.println(c);

    }
    }


  • Faiz

    import java.util.*;

    public class bari {

    public static void solution(int[] arr) {
    HashSet set = new HashSet();

    for (int i : arr) {
    set.add(i);
    }

    int count = set.size();

    System.out.println(“Distinct element in array is : ” + count);
    }

    public static void main(String[] args) {
    int arr[] = new int[] { 10, 40, 50, 20, 10, 20, 30, 10 };

    solution(arr);
    }
    }


  • Ritik

    class Main{
    static int distinctElements(int[] ia){
    int count=1;
    java.util.Arrays.sort(ia);

    for (int i=0,j=1;i<ia.length && j<ia.length ;i++ , j++)
    {
    if(ia[i]==ia[j]){
    continue;
    }
    count++;
    }
    return count;
    }

    public static void main(String[] args){
    int[] ia={4,5,3,7,98,0,2,2,3,5,5,6};
    System.out.println("number of Distinct elements :"+distinctElements(ib));
    }
    }

    MORE PRECISISE ANSWER


  • Debyanshu

    import java.util.*;

    public class Main {
    public static void main(String[] args) {
    int a[]={10, 30, 40, 20, 10, 20, 50, 10};
    System.out.println(map(a));

    }
    static int map(int a[]) {

    HashSet map=new HashSet();
    for (int i = 0; i <a.length ; i++) {
    map.add(a[i]);

    }
    return map.size();

    }
    }


  • Ganpat

    // Finding Distinct numbers from the array
    //Easy method
    import java.util.*;
    class Main{
    public static void main(String [] args){

    int arr[] = {10,20,50,40,50,45,10,60,20};
    int len = arr.length;
    Arrays.sort(arr);

    int count=1;
    for(int i=0; i<len-1; i++){
    if(arr[i] == arr[i+1]){
    continue;
    }
    else{
    count++;
    }
    }
    System.out.println(count);
    }
    }


  • Gyanendra

    import java.util.*;
    public class Find_distinct_element_in_an_array {

    public static void main(String[] args) {
    Scanner scn=new Scanner(System.in);
    int n=scn.nextInt();
    int[] arr=new int[n];
    for(int i=0;i<n;i++) {
    arr[i]=scn.nextInt();
    }

    Map list=new HashMap();

    for(int i=0;i<arr.length;i++) {
    list.put(arr[i],i);
    }
    System.out.println(list.size());

    }

    }


  • 19cs134-

    import java.util.*;

    public class Main {
    public static void main(String[] args) {
    HashSet h= new HashSet();
    Scanner s = new Scanner(System.in);
    int q=5;
    for(int i=0;i< a;i++){
    int temp = s.nextInt();
    h.add(temp);
    }
    System.out.println(h.size());
    }
    }


  • Dhivya

    import java.util.HashSet;
    import java.util.Scanner;

    public class distinctArray {
    public static void main(String[] args) {
    HashSet h= new HashSet();
    Scanner s = new Scanner(System.in);
    int a[]= new int[5];
    for(int i=0;i< a.length;i++){
    a[i]= s.nextInt();

    }
    for(int i=0;i< a.length;i++){
    h.add(a[i]);

    }
    System.out.println(h.size());
    }
    }