Understanding Problem[HORSES]

The Question Link is :-

I understand the Question and i assume he wants minimum difference between two element in an array so my approach was that we can sort the array and the answer will be arr[1]-arr[0] but i saw time limit 0.6 second so, the thought the better solution will be to find the minimum and second minimum element and substract them and that will be the result.
My solution:-
But now i know that my logic is wrong and there is something hidden in the Problem Statement.
Can You help me understanding the Problem.

1 Like

Consider the testcase:

1 10 20 21 25

Thanks You always help me. :slightly_smiling_face:

1 Like

You are assuming that after sorting the difference between arr[1] and arr[0] will be minimum. This assumption is incorrect.
As @ssjgz mentioned for the testcase:

1 10 20 21 25
It can be clearly seen that above approach would give answer as abs(10-1) = 9. But correct answer would be 1 i.e. abs(21-20).
You'll need to iterate over the array.

minDiff = infinity
for i from 0...arr.length-1
    minDiff = min(minDiff, abs(arr[i]-arr[i+1])

My Solution
1 Like