Tag Archives: sorting

Minimum difference between two elements in array

Given an array, how do we find the minimum difference between any two elements in that array?

For example consider the array [56, 18, 89, 24, 10], the minimum difference is 6 (between 18, and 24).

A straight forward method to find the minimum difference between any two pairs is to iterate through each possible pair and find the minimum difference. But this method takes O(n2) time.

This can be solved in O(n log n) time if we sort the array. Since the closest elements are always adjacent to each other in a sorted array, we can find the minimum difference in one iteration. Here is the C++ code for the same.