Minimum Distances

We define the distance between two array values as the number of indices between the two values. Given , find the minimum distance between any pair of equal elements in the array. If no such value exists, print .
For example, if , there are two matching pairs of values: . The indices of the 's are  and , so their distance is . The indices of the 's are  and , so their distance is .
Function Description
Complete the minimumDistances function in the editor below. It should return the minimum distance between any two matching elements.
minimumDistances has the following parameter(s):
  • a: an array of integers
Input Format
The first line contains an integer , the size of array .
The second line contains  space-separated integers .
Constraints
Output Format
Print a single integer denoting the minimum  in . If no such value exists, print .
Sample Input
6
7 1 3 4 1 7
Sample Output
3
Explanation
Here, we have two options:
  •  and  are both , so .
  •  and  are both , so .
The answer is .

php

<?php

// Complete the minimumDistances function below.
function minimumDistances($a) {
$mind = count($a);
$v = false;
for($i = 0; $i < count($a) -1; $i++) {
for($j = $i+1; $j < count($a); $j++) {
if(abs($a[$i] - $a[$j]) == 0) {
if(abs($i - $j) < $mind) {
$mind = abs($i - $j);
}
$v = true;
}
}
}
return $v ? $mind: -1;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$stdin = fopen("php://stdin", "r");

fscanf($stdin, "%d\n", $n);

fscanf($stdin, "%[^\n]", $a_temp);

$a = array_map('intval',
preg_split('/ /', $a_temp, -1, PREG_SPLIT_NO_EMPTY));

$result = minimumDistances($a);

fwrite($fptr, $result . "\n");

fclose($stdin);
fclose($fptr);

Comments

Popular posts from this blog

Intro to Tutorial Challenges

Mini-Max Sum