Minimum Distances ⬀
The distance between two array values is the number of indices between them. Given a, find the minimum distance between any pair of equal elements in the array. If no such value exists, return -1.
a = [3, 2, 1, 2, 3]
There are two matching pairs of values: 3 and 2. The indices of the 3's are i = 0 and j = 4, so their distance is d[i, j] = |i - j| = 4. The indices of the 2's are i = 1 and j = 3, so their distance is d[i, j] = |j - i| = 2. The minimum distance is 2.
Complete the minimumDistances function in the editor below.
minimumDistances has the following parameter(s):
int a[n]: an array of integers
int: the minimum distance found or-1if there are no matching elements
The first line contains an integer n, the size of array a.
The second line contains n space-separated integers a[i].
1 ≤ n ≤ 10³1 ≤ a[i] ≤ 10⁵
Print a single integer denoting the minimum d[i, j] in a. If no such value exists, print -1.
STDIN Function
----- --------
6 arr[] size n = 6
7 1 3 4 1 7 arr = [7, 1, 3, 4, 1, 7]
3
There are two pairs to consider:
a[1]anda[4]are both1, sod[1, 4] = |1 - 4| = 3.a[0]anda[5]are both7, sod[0, 5] = |0 - 5| = 5.
The answer is min(3, 5) = 3.