




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.
1#include <vector>
2using namespace std;
3
4bool checkStraightLine(vector<vector<int>>& coordinates) {
5    int x1 = coordinates[0][0], y1 = coordinates[0][1];
6    int x2 = coordinates[1][0], y2 = coordinates[1][1];
7    for (size_t i = 2; i < coordinates.size(); ++i) {
8        int x = coordinates[i][0], y = coordinates[i][1];
9        if ((y2 - y1) * (x - x1) != (y - y1) * (x2 - x1)) {
10            return false;
11        }
12    }
13    return true;
14}The C++ solution uses a for-loop to calculate and compare the cross product terms for slope equality, ensuring all points are collinear with the first two points.
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
In Python, this solution uses consecutive point subtraction and subsequent cross product assessments to ensure that all points align perfectly on a direct path.