




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.
1var checkStraightLine = function(coordinates) {
2    const [x1, y1] = coordinates[0];
3    const [x2, y2] = coordinates[1];
4    for (let i = 2; i < coordinates.length; i++) {
5        const [x, y] = coordinates[i];
6        if ((y2 - y1) * (x - x1) !== (y - y1) * (x2 - x1)) {
7            return false;
8        }
9    }
10    return true;
11};The JavaScript solution uses a for loop, calculating cross product differences to confirm the presence of a straight line. Its use of ES6 destructuring makes variable assignments compact.
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.
The JavaScript implementation calculates differential coordinates before performing cross-product consistency-driven checks that confirm all input points share a composite line.