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 →

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.