I look at this problem like this.
For [a,b,c,d] such a<b<c<d and x,y,z>0 and b = a+x, c = b+y, d=c+z, then b-a = x, c-b = y, c-a = x+y, d-b = y+z, d-a = x+y+z.
What does it tell us? The more apart are the elements the bigger the difference, and it adds up with every step.
It is unknown if x<y or x>y but for sure x+y>x and x+y>y, so your differences can be divided into distance classes.
diff_1 = {d-c,c-b,b-a}, diff_2 = {d-b,c-a}, diff_3={d-a}
now what you probably can see by now is min(diff_1) < min(diff_2) < min(diff_3), so to find the second smallest difference you don't need to check for min(diff_3) because it is at best the third smallest element.
So what you do is to implement something like this pseudocode:
int findLeastDiff<k>(std::vector<int> v)
{
assert(v_contains_k_distinct_elements(v));
std::vector<int> result;
std::sort(v.begin(),v.end()); // O(nlog(n));
v.erase(std::unique(v.begin(),v.end()),v.end()); // O(n)
for<<int i=1; i<=k; ++i>>
{
adjacent_difference<i>(v.begin(), v.end(), std::back_inserter(result));// O(n-i)
} // O(k(n-k/2)) = O(k*n)
std::sort(result.begin(), result.begin()); // O(nlog(n));
result.erase(std::unique(result.begin(),result.end()),result.end()); // O(n)
return result[k];
}
The above is just a concept and for sure can be optimized a lot. What is the complexity? O(nlog(n)+n+k*n+nlog(n)+n) = O((2log(n)+k+2)*n)
It probably can be optimized with some clever way of reducing the search space by removing ranges with already too big differances.