The question I'm thinking about is this:
Say we have a sorted array with numbers {1,1,1,1,2,2,4,4,4}.
Now, given that we can clearly see that we have six pairs of 1, one pair of two and three pairs of 4 (10 pairs). How would you build an algorithm that finds these pairs in O (n)?
I have an algorithm that counts pairs in an array and does it like this:
Arrays.sort(array);
int counter = 0;
for(int i = 0; i<array.length; i++) {
for(int j = i+1; j<array.length; j++) {
if(j!=i && array[j] == array[i]) {
counter++;
}
}
}
return counter;
Run codeHide resultBut this works in O (N ^ 2), and I assume (being a beginner that I am with algorithms) that there is a better solution to get the same results using only one for or loop while loop?
I would love to hear your thoughts!
source
share