Skip to content
Programming101
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programmingoneonone

Learn everything about programming

HackerRank Minimum Distance problem solution

YASH PAL, 31 July 2024

In this HackerRank Minimum Distance problem you have Given a, find the minimum distance between any pair of equal elements in the array. If no such value exists, return -1.

HackerRank Minimum Distance problem solution

Problem solution in Python programming.

class Solution:
    def __init__(self):
        self.size = int(input())
        self.array1 = get_int_list(input())

    def calculate(self):
        val_dict = {}
        for i,val in enumerate(self.array1):
            if val in val_dict:
                val_dict[val].append(i)
            else:
                val_dict[val]=[i]
        min_val = None
        for indices in val_dict.values():
            if len(indices) > 1:
                for i in range(0,len(indices)-1):
                    if min_val is None or (indices[i+1]-indices[i]) < min_val:
                        min_val = indices[i+1]-indices[i]
        if min_val is None:
            return -1
        else:
            return min_val


def main():
    my_object = Solution()
    print(my_object.calculate())


def get_int_list(in_str):
    return [int(i) for i in in_str.strip().split()]


if __name__ == "__main__":
    main()

Problem solution in Java Programming.

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

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[] = new int[n];
        for(int i=0; i < n; i++){
            a[i] = in.nextInt();
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                if (a[i] == a[j]) {
                    int temp = j - i;
                    if (temp < min) {
                        min = temp;
                    }
                }
            }
        }
        if (min == Integer.MAX_VALUE)
            min = -1;
        System.out.println(min);
    }
}

Problem solution in C++ programming.

#include <bits/stdc++.h>

#define all(x) (x).begin(), (x).end()
#define li long long
#define itn int

using namespace std;

inline int nxt(){
    int n;
    scanf("%d", &n);
    return n;
}

int gcd(int x, int y){
    while (y){
        x %= y;
        swap(x, y);
    }
    return x;
}

const int mod = 1000000007;

int main(){

    int n = nxt();
    vector<int> a(n);
    for (int i = 0; i < n; i++){
        a[i] = nxt();
    }

    int ans = -1;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < i; j++){
            if (a[i] == a[j]){
                if (i - j < ans || ans == -1)
                    ans = i - j;
            }
        }
    }

    cout << ans << "n";

    return 0;
}

Problem solution in C programming.

#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;
    int distance = 1001;
    scanf("%d",&n);
    int *A = malloc(sizeof(int) * n);
    for(int i = 0; i < n; i++){
       scanf("%d",&A[i]);
    }
    
    
    for(int i = 1; i < n; i++){
       for(int j=i-1;j>=0;j--)
       {
           if(A[i]==A[j])
           {
               if(i-j < distance)
                   distance = i-j;
               break;
           }
       }
    }
    
    if(distance == 1001)
        distance = -1;
    
    printf("%dn",distance);
    return 0;
}

Problem solution in JavaScript programming.

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    readLine()
    i=readLine().split` `
    r=[]
    i.map((x,y,z)=>(z.slice(0).splice(y,1),~(I=z.indexOf(x))&&r.push(Math.abs(y-I))))
    console.log(Math.min(...r.filter(x=>x).length>0?r.filter(x=>x):[-1]))
}

Algorithms coding problems solutions

Post navigation

Previous post
Next post
  • Automating Image Format Conversion with Python: A Complete Guide
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
How to download udemy paid courses for free

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes