Say the line has slope . If a point’s slope with a point on the line is
, the new point is also on the line. For each pair of consecutive points we check if they have the same slope.
With points, time:
, space:
.
class Solution:
def slope(self, a, b):
dy = b[1] - a[1]
dx = b[0] - a[0]
return dy/dx if dx != 0 else float("inf")
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
slope = None
for i in range(1, len(coordinates)):
a = coordinates[i-1]
b = coordinates[i]
m = self.slope(a, b)
if slope is None:
slope = m
continue
if m != slope:
return False
return True
Leave a comment