We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Exactly, this just compares 'neighbors' i.e. numbers at consecutive indices (i, i+1)...that's a set of O(n) whereas the set of all possible pairs (given by, for example, set([i, i for i in range(n)]).symmetric_difference(itertools.product(a, a)) is O(n^2)

Note that the array was sorted beforehand, so that considering differences of consecutive elements is all we need to check to find the minimum difference.
No point in checking the difference between i and i+2 if we know the difference between i and i+1 is definitely less.

## Minimum Absolute Difference in an Array

You are viewing a single comment's thread. Return to all comments →

Yeah, it was pretty easy after reading your comment.

Check for duplicates helps to avoid unnecessary computations.

This is relevant for one of the tests.

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:

it's really nice!

you are not considering all pairs, zip is not useful in this case

Exactly, this just compares 'neighbors' i.e. numbers at consecutive indices (i, i+1)...that's a set of O(n) whereas the set of all possible pairs (given by, for example, set([i, i for i in range(n)]).symmetric_difference(itertools.product(a, a)) is O(n^2)

Note that the array was sorted beforehand, so that considering differences of consecutive elements is all we need to check to find the minimum difference. No point in checking the difference between i and i+2 if we know the difference between i and i+1 is definitely less.