Recently I had an interview question to write an algorithm which analyse an array and returns numbers which are duplicates;
My brute force solution was:
public static ArrayList getDuplicates (int[] input){
ArrayList duplicates = new ArrayList();
int marker = 0;
for (int i = marker + 1; (i < input.length) && (marker < input.length - 1); i++){
if (input[marker] == input[i]){
duplicates.add(input[marker]);
marker++;
continue;
} else {
if (i == input.length - 1){
marker++;
i = marker;
}
continue;
}
}
return duplicates;
}
Without thorough analysis I gave a reply that the Big O is n*(log (n)).
After interview I checked again and found that it was not a correct answer.
The confusing part is that algorithm is repeated, however not for n times but every cycle for n-k times where k = {1..n-1}. This is a part which reset a moving index:
if (i == input.length - 1){
marker++;
i = marker;
}
What is a best approach to analyse this algorithm to find a correct Big O function?