I was trying to solve a coding problem https://www.hackerrank.com/challenges/minimum-distances/problem (Given a list find the minimum distance between any two equal elements)
Wrote this code, which does not pass some tests.
public static int minimumDistances(List<Integer> a) {
int min = Integer.MAX_VALUE; boolean hasPair = false;
for(int i = 0 ; i < a.size()-1; i ++){
for(int j = i+1; j < a.size() ; j++){
if(a.get(i) == a.get(j) && j-i < min){
min = j-i;
hasPair = true;
}
}
}
if(!hasPair)
min = -1;
return min;
}
}
But when extracted the a.get(i)
into a variable before the inner loop and using that variable in the inner loop made the test cases pass. Now I am not able to understand what is the difference, is there any optimisation happening at assembly level or so to give different results ?
This code makes all the tests pass (i was able to reproduce this in my local machine too)
public static int minimumDistances(List<Integer> a) {
int min = Integer.MAX_VALUE; boolean hasPair = false;
for(int i = 0 ; i < a.size()-1; i ++){
int current = a.get(i);
for(int j = i+1; j < a.size() ; j++){
if(current == a.get(j) && j-i < min){
min = j-i;
hasPair = true;
}
}
}
if(!hasPair)
min = -1;
return min;
}
}
When you are doing a.get(i) == a.get(j)
, it does refference comparison, which basically states whether they are the same object or not.
But in the second approach, when you are doing current == a.get(j)
, as the first parameter is a primitive type, then auto unboxing happening for the 2nd object, results in a comparison between two primitive data, which compares the values. That's why 2nd case is passing all the cases.
Now, there is a catch. As you might have seen, while running your first code, it's giving the right answer to your inputs. That's because Integer between -128 and 127, has same references as Java caches this specific small range of values and only uses a single object no matter how many times new objects are created with these values. So when you check your first code with inputs from this range, your program will run just fine.