Real Networks Interview Question
Software Engineer / Developerssorting by any means other tha counting sort cannot be less than O(nlogn)..
whereas counting sort give it in O(n) at the cost of space.\
this sorting technique is applicable when we know the range of data.
i hope i have explained it well now.
I am not really sure why sorting is necessary at all since all we have to do is find out the frequency of each number in the array.
I would go for hashing the array where the key=number and value=frequency of number.
Hashing and printing the values would take n+n time=O(n) time and also due to the hash table O(n) space complexity
What saumil suggests is using the counts from the counting sort stage. since the range 1-50 is known we can store in a array the counts.
Hash approach sugested by someone else is exactly the same but it is typically better to use an array if the range is known. Think of a Array as the Perfect hash.
What saumil suggests is using the counts from the counting sort stage. since the range 1-50 is known we can store in a array the counts.
Hash approach sugested by someone else is exactly the same but it is typically better to use an array if the range is known. Think of a Array as the Perfect hash.
How abt this approach??
for(int i = 0 ; i < n ; i++){
a[a[i]] = a[i]+(a[a[i]]%a[i]);
}
for(int i = 0 ; i < 50 ; i++){
cout << "no of occurances of" << i << ": ";
int occur = a[i]/i;
if(a[i]%i == 0)
occur--;
cout << occur << endl;
}
correct if this is inefficient
I think you can't modify Original Array (because if you do this then, how to count freq. of modified values )...we need to have another array...and this leads us o(n) extra space...
perform counting sort and create an integer array of length 50.
- saumils1987 August 31, 2010that would surely do the job..