HashSet hs= new HashSet(); for (Integer x: inputArray){ hs.add(x); } s.o.p(hs.size());

//If input: 1,2,3,1,4,6,3,7,8,9,0. Then your code will return 9, but it should return 7. //Improved code Set distinctSet = new HashSet(); for(int i = 0; i<array.length; i++){ if(!(distinctSet.contains(array[i]))){ distinctSet.add(array[i]); } else{ distinctSet.remove(array[i]); } } System.out.println(distinctSet.size());

Hi Hiten, the answer should return 9 instead of 7, cuz you want to find the distinct number, this hashset should have 1,2,3,4,6,7,8,9,0, which have 9 elements inside

number of distinct integers in array = number of integers in array - number of duplicate integers number of integers in array = length of array So, this becomes a problem of finding the number of duplicates. This can be accomplished in O(N) time using the following algo: public static void countDistinct(int[] arr){ //numbers are b/w 1-100 boolean[] hit = new boolean[100]; int dup = 0; for(int i=0;i<arr.length;i++){ if(hit[arr[i]] == true){ //duplicate dup++; continue; } hit[arr[i]] = true; } System.out.println("Distinct:"+(arr.length-dup)); }

public static int distinct(int a[]){ boolean map[] = new boolean[100]; int dup=0; for(int i=0;i<a.length;i++){ if(map[a[i]]){ dup++; } else map[a[i]]=true; } return a.length-dup; }

int distinct(int []x) { bool []count= new bool[100]; int n = x.Length; for (int i = 0; i < x.Length; ++I) { if(count[x[i]]) n--; count[x[i]] = true; } return n; }

Use a set. Iterate through the array and insert each element in a set. then get set.size()