Minimum Distances HackerRank Solution in C, C++, Java, Python

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.

Example

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]=|j-i|=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.

Function Description

Complete the minimumDistances function in the editor below.

minimumDistances has the following parameter(s):

int a[n]: an array of integers

Returns

int: the minimum distance found or -1 if there are no matching elements

Input Format

The first line contains an integer n, the size of array a.
The second line contains n space-separated integers a[i].

Output Format

Print a single integer denoting the minimum in . If no such value exists, print .

Sample Input

STDIN Function
----- --------
6 arr[] size n = 6
7 1 3 4 1 7 arr = [7, 1, 3, 4, 1, 7]

Sample Output

3

Minimum Distances HackerRank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n,i,j,min=100000; 
    scanf("%d",&n);
    int *a = malloc(sizeof(int) * n);
    for(int i = 0; i < n; i++){
       scanf("%d",&a[i]);
    }
    for(i=0;i<n-1;i++){
        for(j=i+1;j<n;j++)
            if(a[i]==a[j] && j-i<min)
            min=j-i;
    }
    if(min==100000)
        min=-1;
    printf("%d",min);
    return 0;
}

 

Minimum Distances HackerRank Solution in C++

#include <stdio.h>
#include <algorithm>
#include <assert.h>
#include <set>
#include <map>
#include <complex>
#include <iostream>
#include <time.h>
#include <stack>
#include <stdlib.h>
#include <memory.h>
#include <bitset>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>

using namespace std;

const int MaxN = 1e5 + 10;
const int MOD = 1e9 + 7;
const int INF = 1e9;

int main() {
//  freopen("input.txt", "r", stdin);
  int n;
  scanf("%d", &n);
  int ans = n;
  map < int, int > last;
  for (int i = 1; i <= n; ++i) {
    int x;
    scanf("%d", &x);
    if (last.count(x)) {
      ans = min(ans, i - last[x]);
    }
    last[x] = i;
  }
  cout << (ans == n ? -1 : ans) << '\n';
  return 0;
}

 

Minimum Distances HackerRank Solution in Java

/* Andy Rock
 * June 25, 2016
 * 
 * World CodeSprint #4
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(in.readLine());

        StringTokenizer st = new StringTokenizer(in.readLine());
        int[] A = new int[n];
        for(int i=0;i<n;i++)
            A[i] = Integer.parseInt(st.nextToken());

        int ans = Integer.MAX_VALUE;
        for(int i=0;i<n;i++)
            for(int j=i+1;j<n;j++)
                if(A[i] == A[j] && j - i < ans)
                    ans = j - i;

        System.out.println(ans == Integer.MAX_VALUE? -1 : ans);
    }
}

 

Minimum Distances HackerRank Solution in Python

#!/bin/python

import sys


n = int(raw_input().strip())
A = map(int,raw_input().strip().split(' '))
r=n+1
for i in range(n):
    for j in range(i+1,n):
        if A[j]==A[i]:
            r=min(j-i,r)
if r<=n:
    print r
else:
    print -1

 

Minimum Distances HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {

    static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());
        string[] A_temp = Console.ReadLine().Split(' ');
        int[] A = Array.ConvertAll(A_temp,Int32.Parse);
        
        int min = int.MaxValue;
        for(int i=0;i<n-1;i++){
            for(int j=i+1;j<n;j++){
                if(A[i]==A[j]){
                    int d = j-i;
                    if(d<min)min=d;
                }
            }
        }
        if(min==int.MaxValue) Console.WriteLine(-1);
        else Console.WriteLine(min);
    }
}

 

Attempt Minimum Distances HackerRank Challenge

Link – https://www.hackerrank.com/challenges/minimum-distances/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/halloween-sale-hackerrank-solution/

Leave a Comment