Skip to main content

Posts

Featured

Find the count of distinct elements in an array

Find the count of distinct elements in an array 1 123 2 413 2 5 1 2 4 Result: 6 This is an interesting problem and has got different solutions. The factors to consider are: 1) Size of the input 2) Range of input e.g. 1 to 100 3) Can we use additional resources i.e. memory or not There are different ways we can solve this problem: Solutions 1: The first solution iterates through the elements and checks if the element is already counted as distinct element. This solution does not consider the input range or size and is computationally expensive. //Array int [] values = { 1 , 2 , 3 , 4 , 2 , 1 , 5 , 7 }; //set the distinct count as 0 var distinctCount = 0 ; //iterate through all the elements for ( int i = 0 ; i < values . Length ; i ++) { //Take it as the it is a new element and increase the distinct count distinctCount ++; var alreadyCounted = false ; //check if the element is already counted ...

Latest posts

I, me and myself!