![]() |
VOOZH | about |
Given three points, check whether they lie on a straight (collinear) or not
Examples :
Input : (1, 1), (1, 4), (1, 5) Output : Yes The points lie on a straight line Input : (1, 5), (2, 5), (4, 6) Output : No The points do not lie on a straight line
First approach
Three points lie on the straight line if the area formed by the triangle of these three points is zero. So we will check if the area formed by the triangle is zero or not
Formula for area of triangle is : 0.5 * [x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)] The formula is basically half of determinant value of following. x1 x2 x3 y1 y2 y3 1 1 1 The above formula is derived from shoelace formula. If this equals zero then points lie on a straight line
Output :
Yes
Time Complexity: O(1)
Auxiliary Space: O(1)
Second approach
For three points, slope of any pair of points must be same as other pair. For example, slope of line joining (x2, y2) and (x3, y3), and line joining (x1, y1) and (x2, y2) must be same. (y3 - y2)/(x3 - x2) = (y2 - y1)/(x2 - x1) In other words, (y3 - y2)(x2 - x1) = (y2 - y1)(x3 - x2)
Output :
No
Time Complexity: O(1)
Auxiliary Space: O(1)