Friday, 28 August 2020

Minimum Distances Hacker Rank Solution in C, C++

https://www.hackerrank.com/challenges/minimum-distances/problem

#include<stdio.h>
#include<limits.h>
int main()
{
    int n,ans=INT_MAX;
    int m[100008]={0};
    scanf("%d",&n);
    int temp;
    for(int i=1;i<=n;i++) // i has to start with 1 otherwise m[temp]=i will update
                            //m[temp] to zero and if(m[temp] == 0) will become true
                            // example:2 1 1                                    
    {
        scanf("%d",&temp);
        if( m[temp] == 0)
            m[temp]=i;
        else 
        {
            int previndex = m[temp];
            if(ans> i-previndex)
                ans=i-previndex;
        }
    } 
    if(ans == INT_MAX)
        printf("-1");
    else
        printf("%d",ans);
}   

=============================in C++==========================

#include <bits/stdc++.h>

using namespace std;
int main()
{
    int n,ans=INT_MAX;
    map<int,int>m;
    scanf("%d",&n);
    int a[n];
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        if( m.find(a[i]) == m.end())
            m[a[i]]=i;
        else 
        {
            int previndex = m[a[i]];
             ans=min(ans,abs(i-previndex));
        }
    } 
    if(ans == INT_MAX)
        printf("-1");
    else
        printf("%d",ans);
}   

No comments:

Post a Comment