I am looking for a faster way to find whether an array of elements contains distinct elements only. The worst thing to do is to take each element and compare it to every other element in the array. Next best would be to sort the list and then compare, which still does not improves this much. Is there any other way to do this?
One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.
Using an object or Map and initialising only the values that appear in the array might be faster and won't fail if the assumptions (like age being an integer between 0 and 200) are not met.
Step 1 − Declare an array and input the array elements at run time. Step 2 − Start traversing the array and check, if the current element is already present in an array or not. Step 3 − If it is already present in an array then, move to the next element in an array and continue.
Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements. Print the result.
Brute-force:
Brute-force (checking every element with every other element) takes O(n2)
.
Sorting:
Sorting takes O(n log n)
, which is generally considered to be a fairly decent running time.
Sorting has the advantage above the below (hash table) approach in that it can be done in-place (O(1)
extra space), where-as the below takes O(n)
extra space.
Hash table:
An alternative is to use a hash table.
For each item:
Since insert and contains queries run in expected O(1)
on a hash table, the overall running time would be expected O(n)
, and, as mentioned above, O(n)
extra space.
Bit array:
Another alternative, if the elements are all integers in some given range, is to have a bit array with size equal to the range of integers.
Similarly to what was done for the hash table approach, for each element, you'd check whether the applicable bit is set, and then set it.
This takes O(m + n)
time and O(m)
extra space where m
is the range of integers and n
is the size of the array (unless you consider allocating the array to be free, in which case it just takes O(n)
time).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With