You are viewing a single comment's thread. Return to all comments →
Check for duplicates helps to avoid unnecessary computations.
if len(arr) != len(list(set(arr))):
result = 0
This is relevant for one of the tests.
Full python solution.
Hackerrank - Minimum Absolute Difference in an Array Solution
also a nice profile.
here is problem solution in python java c++ and C programming.
to avoid even more unnecessary computations:
len(list(set(arr))) -> len(set(arr))
You can also abort when diff is zero to pass the test.
Not sure how relevant, this passes all tests:
diffs = 
for i in range(len(arr)-1):
Don't append the diffs. You are just incresing the space complexity. Also you are taking the min(diffs). In the background this is another for loop, so your time complexity increses by O(n).
Just take a variable, maybe name it diffs. Every time you encounter a new min, update the diffs, and finally return it.
bcoz, sorting of array will bring small value element near, thus their diff also min.
suppose if didn't apply sort..
n = 4
arr = 2 34 68 1
in this case 2 and 1 are not near so their diff will not be calaculate by the loop(as per ur logic).
My 1-line Python3 solution (passes all testcases) is similar but no abs or append.
A.sort() ; return min( A[i+1]-A[i] for i in range(n-1) )
The native list sort is done in O(n log n) time; the naïve approach is O(n^2).
O(n log n)
That list by comprehension is equivalent to building it by appending. The space complexity is the same.
In this case, if the "list by comprehension" to which you refer is presumably that which is inside the min function, then your assertion is false.
Here in Python3, a generator is being passed to the min function, so no list is being created in memory for it. Elements are being discovered through lazy evaluation of the formula. The minimum is a greedy operation running over the indices i, so it does not store the previous values a[i+1]-a[i] as it proceeds forward. It just finds the minimum up to that point when the i-th term is considered.
Yes, that is right. There is not a list by comprehension but only a generator.