You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true
Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false
Constraints:
2 <= coordinates.length <= 1000coordinates[i].length == 2-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4coordinates contains no duplicate point.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.
This C solution checks the constancy of slope using cross multiplication to avoid division and potential floating point precision issues. It iterates through all points starting from the third point and compares the calculated product terms for collinearity.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of points.
Space Complexity: O(1), as we use a fixed number of extra variables.
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.
This C solution utilizes the vector cross-product to determine if any vectors are non-collinear by checking if the cross-product between consecutive points remains zero.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n refers to the number of coordinates.
Space Complexity: O(1), as only constant additional space is used.
| Approach | Complexity |
|---|---|
| Approach 1: Using Slope Comparison | Time Complexity: O(n), where n is the number of points. |
| Approach 2: Vector Cross Product | Time Complexity: O(n), where n refers to the number of coordinates. |
Check If It Is a Straight Line | Leetcode #1232 | Find if all coordinate points form a straight line • Techdose • 20,523 views views
Watch 9 more video solutions →Practice Check If It Is a Straight Line with our built-in code editor and test cases.
Practice on FleetCode