1232 Check If It Is a Straight Line - Easy
Problem:
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.
Problem Analysis:
-
Base case: if there are only 2 points, it is guaranteed true
-
Find the slope of the first 2 points
-
Return true if all the slope between points are the same
-
Time Complexity: O(n)
-
Space Complexity: O(1)
Solutions:
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
if len(coordinates) <= 2:
return True
# calculate slope
x0, y0 = coordinates[0]
x1, y1 = coordinates[1]
initial_slope = (y1 - y0) / (x1 - x0) if (x1 - x0) != 0 else float('inf')
# check slope
for i in range(2, len(coordinates)):
xi, yi = coordinates[i]
current_slope = (yi - y0) / (xi - x0) if (xi - x0) != 0 else float('inf')
# if slope dont match
if current_slope != initial_slope:
return False
return True```
## Similar Questions