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 <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
contains no duplicate point.
Solution
Intuition
The slope of a line is (y2 – y1) / (x2 – x1). If the slope of the line is the same for all points, then the points are on the same line.
Runtime
0 ms
Beats
100%
Accepted Solutions Runtime Distribution (%)
Memory
41.8 MB
Beats
94.86%
Approach
We can use the slope of the first two points to check if the rest of the points are on the same line. If the slope is the same for all points, then the points are on the same line.
Complexity
- Time complexity: O(N)
- Space complexity: O(1)
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int x1 = coordinates[0][0];
int y1 = coordinates[0][1];
int x2 = coordinates[1][0];
int y2 = coordinates[1][1];
for(int i = 2; i < coordinates.length; i++){
int x = coordinates[i][0];
int y = coordinates[i][1];
if((y2 - y1) * (x - x1) != (y - y1) * (x2 - x1)){
return false;
}
}
return true;
}
}
Happy Learning – If you require any further information, feel free to contact me.