




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.
1class Solution {
2    public boolean 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}The Java solution loops through the array, leveraging cross multiplication to ensure no slope division, thus checking for point 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.
1    public bool CheckStraightLine(int[][] coordinates) {
        int dx = coordinates[1][0] - coordinates[0][0];
        int dy = coordinates[1][1] - coordinates[0][1];
        for (int i = 2; i < coordinates.Length; i++) {
            int x = coordinates[i][0] - coordinates[0][0];
            int y = coordinates[i][1] - coordinates[0][1];
            if (dx * y != dy * x) return false;
        }
        return true;
    }
}This C# strategy approaches line determination via vector subtraction followed by cross product stability checks between consecutive coordinates. It's directly computed without coordinate division.