




Sponsored
Sponsored
In this approach, we calculate the slope between the first two points and then compare this slope with that of subsequent points. The slope between two points (x1, y1) and (x2, y2) is given by (y2-y1)/(x2-x1). For all points to lie on the same line, this slope should be constant for every pair of consecutive points.
Time Complexity: O(n), where n is the number of points.
Space Complexity: O(1), as we use a fixed number of extra variables.
1public class Solution {
2    public bool CheckStraightLine(int[][] coordinates) {
3        int x1 = coordinates[0][0], y1 = coordinates[0][1];
4        int x2 = coordinates[1][0], y2 = coordinates[1][1];
5        for (int i = 2; i < coordinates.Length; i++) {
6            int x = coordinates[i][0], y = coordinates[i][1];
7            if ((y2 - y1) * (x - x1) != (y - y1) * (x2 - x1)) {
8                return false;
9            }
10        }
11        return true;
12    }
13}This C# solution iterates over the array, utilizing the cross multiplication technique to avoid floating point arithmetic mistake, thus determining line collinearity.
This approach uses the cross-product method which is useful for determining collinearity without explicitly calculating slopes. For every pair of consecutive vectors, compute the cross product to determine if they are collinear. If all cross products are zero, the points are collinear.
Time Complexity: O(n), where n refers to the number of coordinates.
Space Complexity: O(1), as only constant additional space is used.
1The Java solution employs vector subtraction and a structured cross-product for every pair of points, allowing for composite line determination without fixed slope measures.