The following is an interview question which I’ve tried hard to solve. The required bound is to be less than O(n^2). Here is the problem:
You are given with a set of points S =
(x1,y1)....(xn,yn). The points
are co-ordinates on the XY plane. A point(xa,ya)is said to be
greater than point(xb,yb)if and only ifxa > xbandya > yb.
The objective is the find all pairs of points p1 = (xa,ya) and p2 = (xb,yb) from the set S such that p1 > p2.
Example:
Input S = (1,2),(2,1),(3,4)
Answer: {(3,4),(1,2)} , {(3,4),(2,1)}
I can only come up with an O(n^2) solution that involves checking each point with other. If there is a better approach, please help me.
I am assuming you actually want to count such pairs.
Sort descendingly by
xinO(n log n). Now we have reduced the problem to a single dimension: for each positionkwe need to count how many numbers before it are larger than the number at positionk. This is equivalent to counting inversions, a problem that has been answered many times on this site, including by me, for example here.The easiest way to get
O(n log n)for that problem is by using the merge sort algorithm, if you want to think about it yourself before clicking that link. Other ways include using binary indexed trees (fenwick trees) or binary search trees. The fastest in practice is probably by using binary indexed trees, because they only involve bitwise operations.If you want to print the pairs, you cannot do better than
O(n^2)in the worst case. I would be interested in an output-sensitiveO(num_pairs)algorithm too however.