A question that has me speculating is the following:
Let's say we have a sorted array with the numbers {1,1,1,1,2,2,4,4,4}.
Now, given that we can clearly see that we have six pairs on 1's, one pair of 2's and three pairs of 4's (10 pairs). How would you construct an algorithm that finds these pairs in O(n)?
I have an algorithm that counts the pairs in an array and does so 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;
But this runs in O(N^2) and I guess (being the novice that I am with algorithms) that there's a better solution to this to get the same results using only one for-loop or multiple while-loops?
I'd like to hear your thoughts!
6
pairs of1
you mention, do you mean4 choose 2 = 6
? How are there2
pairs of2
? Please explain in more detail. – Attachmentn choose 2
. It is now changed to "occurrence of numbers", but that changes the problem slightly. – Darkish