Given a list of coordinates in the first quadrant, calculate how many right triangles can be formed from these which have one side parallel to x-axis and one side parallel to y-axis.
Recently I took part in a programming competition, more specifically INOI(Indian National Olympiad n Informatics) and this was the first out of two questions in the paper.
Basically I figured any 3 points of type (a,y) (x,y) (x,b) would form such a triangle but couldn’t manage anything better, and in the end just wrote a naive O(n^3) solution (and so did all my friends).
Can anyone suggest a better way?
And please, THIS IS NOT HOMEWORK.
Lets
numX[i] = how many points have i as their X coordinateandnumY[i] = how many points have i as their Y coordinate.We will count how many triangles with the required property exist for a certain point
p. Without loss of generality, we can assume thatpis the point where the triangles make their right angle.For this to happen, we need a point with the same
Ycoordinate and one with the sameXcoordinate. So how about this algorithm:Basically, we can combine each point with the same
Xcoordinate with each point with the sameYcoordinate to get the required triangle. We subtract1so as not to countpitself.This will run in
O(n).