HackerRank : Stryker Codesprint- Minimum Index Difference

By | September 17, 2016

Given two arrays, and , of size that both contain permutations of the same set of unique integers, find and print the number having the absolute minimum index difference between the two arrays. In the event of a tie, choose the smallest number.

Input Format

The first line contains an integer, , denoting the size of the array.
The second line contains space-separated integers describing array (i.e., ).
The third line contains space-separated integers describing array (i.e., ).

Constraints

  • where and correspond to elements in and , respectively.

Output Format

Print the number having the absolute minimum index difference between the two arrays. In the event of a tie, choose the smallest number.

Sample Input

6
9 5 1 21 32 8
21 32 9 8 5 1

Sample Output

8

Explanation

As you can see, the minimum index difference is and there are two numbers, and , having this minimum index difference. As is the smaller of the two numbers, we print as our answer.

Solution

package strykerCodesprint;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Scanner;

public class MinimumIndexDifference {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n= scan.nextInt();
 int a[]= new int[n];
 int b[]= new int[n];
Map<Integer,Integer> map= new LinkedHashMap<Integer,Integer>();
 for(int i=0;i<n;i++)
 a[i]=scan.nextInt();

for(int i=0;i<n;i++)
 b[i]=scan.nextInt();
int min=Integer.MAX_VALUE;
for(int i=0;i<n;i++)
 {
 for(int j=0;j<n;j++)
 {
 if(a[i]==b[j])
 {
 int diff=Math.abs(i-j);
 map.put(a[i],diff);
 if(diff<min)
 min=diff;
 }
 }
 }
int minkey=Integer.MAX_VALUE;
 for(Entry<Integer,Integer> entry: map.entrySet())
 {
 if(entry.getValue()==min)
 {
 if(minkey>entry.getKey())
 minkey=entry.getKey();
 }
 }
 System.out.println(minkey);
 }
}