Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Create index pairs variations for all indexes that pair are unique – it means when (i, j)
exists (j, i)
is the same. Filter only this pairs of indexes, which have the same value. Make an absolute difference of them |i-j|
and choose the minimum value. if there are not differences, print -1
.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.*; public class MinimumDistances { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++) { array[i] = stdin.nextInt(); } int min = Integer.MAX_VALUE; for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { if(array[i] == array[j]) { min = Math.min(min, Math.abs(j - i)); } } } int result = (min == Integer.MAX_VALUE ? -1 : min); System.out.println(result); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
'use strict'; const processData = input => { const lines = input.split('\n'); const array = lines[1].split(' ').map(i => parseInt(i)); let min = 999999999; for(let i = 0; i < array.length - 1; i++) { for(let j = i + 1; j < array.length; j++) { if(array[i] == array[j]) { min = Math.min(min, Math.abs(j - i)); } } } const result = (min === 999999999 ? -1 : min); console.log(result); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 |
object MinimumDistances extends App { val lines = Source.stdin.getLines().toList val array = lines(1).split(" ").map(_.toInt) val indexPairs = array.indices.flatMap(i => array.indices.slice(i + 1, array.length).map(j => (i, j))) val equalValues = indexPairs.filter(pair => array(pair._1) == array(pair._2)) val distances = equalValues.map(pair => (pair._1 - pair._2).abs) val result = if(distances.isEmpty) -1 else distances.min println(result) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 |
n = gets.to_i arr = gets.split(" ").map {|i| i.to_i} min = 99999999 for i in 0..(n-1) for j in (i+1)..n min = [min, (j - i).abs].min if (arr[j] == arr[i]) end end min = -1 if(min == 99999999) puts min |