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.
coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
true
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
contains no duplicate point.To determine if all the points lie on a straight line, we can use the concept of slope. For any two points (x1, y1)
and (x2, y2)
, the slope m
can be calculated as (y2 - y1) / (x2 - x1)
.
Considering the constraints and to avoid division (which can lead to precision issues), we can use cross multiplication to compare slopes instead:
For points (x1, y1)
, (x2, y2)
, and (x3, y3)
, their slopes:
(y2 - y1) / (x2 - x1)
should be equal to (y3 - y1) / (x3 - x1)
The cross multiplication equivalent:
(y2 - y1) * (x3 - x1) == (y3 - y1) * (x2 - x1)
def checkStraightLine(coordinates):
(x0, y0), (x1, y1) = coordinates[0], coordinates[1]
for i in range(2, len(coordinates)):
x, y = coordinates[i]
if (y1 - y0) * (x - x0) != (y - y0) * (x1 - x0):
return False
return True
# Example usage
coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
print(checkStraightLine(coordinates)) # Output: True
The time complexity of this solution is (O(n)), where (n) is the number of points in the coordinates
list. This is because we need to iterate through each point once to check if they all lie on a straight line.
The space complexity is (O(1)) because we are using a constant amount of extra space regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?