Algorithms – Evaluate All Pair Combinations in O(n log n) Time

algorithms

Task – Consider an array of n elements. Count the number of pairs that satisfy condition X (sum of the two elements < an arbitrary number, k) .

The basic approach I could think of would be O(n^2), where I evaluate all n*(n-1)/2 pairs. How can I solve the problem in a better time frame i.e., O(n log n) or less?

The best approach so far was to sort the array, find where a+b smaller than k then add indice of a to solution. But the process still has to go through n-1 'b's to check for each of them. It's better but still doesn't improve the worst case.

Also, this isn't homework. I came across this while preparing for a competition.

Best Answer

if you need ALL results on an arbitrary condition (say C(a,b) = (sha1(a~c)^sha1(c~a))%2 == 0 with ~ as concatenation) then there are n*(n-1)/2 values you need to output that are all independent; so no there is no better way,

but if the result of one pair tells you something about the result of another pair then that information can be used to speed things up. like in your example if sum > k then you sort and for each number you check each in order (forwards or backwards). On the first true result you add the numbers still remaining. This will be O(n log n + r) with r number of true results.

edit: on second thought you can use a binary search each on each number a find the first number that is larger than k-a reducing it to a O(n log n) completely

Related Topic