You are viewing a single comment's thread. Return to all comments →
Can this problem be solved without ever using any sorting algm?
Well you could, by comparing each element with every other element but that'd result in O(n^2)
But that'd be like worse than O(n log n). Guess we could sort by count or radix or bucket to achieve O(n) in sorting
You can't achieve O(n) through bucket sort if you don't know if the input is random. In this problem it is not directly stated. If it was, bucket would seem to be a nice option indeed.
Radix works better for strings, sure longer than 10 digits. Constant factor for such sorting would be unnecessary big, make it slower than qsort.
And you have to be careful with count sort - its speed depends on range of numbers so,
instead of O(n log n) (for qsort n = 10^5) you get O(n) (where n = ai = 10^9).
then count works longer for big input.
Also, for input like
count sort still needs O(10^9) time.
Yes it could be solved in O(n) time, but would require enormous space ~ an array of 2*pow(10,9) locations.
Take the input temp and store it in a location a[temp+1000000000]th location.Next iterate throough the array and find the closest occuring elements. Also, if any element occurs more than once,print 0.
To further increase the process you can take min and max values during the input of the temp. Now you would only have to iterate from min to max values present in the array. And if any element's counter crosses 1, break and output 0.
However, this would not be recommended here due to high space complexity.This has great purposes in other problems.