Tuesday, August 30, 2016

Hackerrank - Minimum Distances

Consider an array of  integers, . The distance between two indices,  and , is denoted by .
Given , find the minimum  such that  and . In other words, find the minimum distance between any pair of equal elements in the array. If no such value exists, print .
Note:  denotes the absolute value of .
Input Format
The first line contains an integer, , denoting the size of array 
The second line contains  space-separated integers describing the respective elements in array .
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 .
Solution:
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int last_index[100001];
  5.  
  6. int main(){
  7.     int n, x;
  8.     scanf("%d"&n);
  9.     int distance = INT_MAX;
  10.     for(int i = 1; i <= n; i++){
  11.         scanf("%d"&x);
  12.         if(last_index[x])distance = min(distance, i-last_index[x]);
  13.         last_index[x] = i;
  14.     }
  15.     if(distance == INT_MAX)distance = -1;
  16.     printf("%d\n", distance);
  17.     return 0;
  18. }

No comments:

Post a Comment