Can anyone tell me the error?


#1

public class Solution {
public int diffPossible(ArrayList A, int B) {
int i,j=0,flag=2;
int l=A.size();
for(i=0;i<l-1;i++){
for(j=i+1;j<l;j++){
if(A.get(j)-A.get(i)==B){
flag=1;
break;
}
else{
flag=0;
}
}
}
return(flag);
}
}


#2

I think as soon as you are getting the correct answer you are just breaking the inner loop while the outer loop still continues for further iterations and overwrites the flag value to 0, instead what you can do is remove else part of the inner loop and initialize the flag value to 0 rather than 2 and then you may get the correct answer. (Still, your solution will be O(n^2) for more optimization use two pointers.)