- categories: Code, Interview Question, leetcode, Easy
- source: https://leetcode.com/problems/check-if-it-is-a-straight-line
- topics: Mathematics
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.
EPS = 10**-4
class Solution(object):
def checkStraightLine(self, coords):
"""
:type coordinates: List[List[int]]
:rtype: bool
"""
# y1 = k * x1 + b => b = y1 - k * x1
# y2 = k * x2 + b => y2 = k * x2 + y1 - k * x1 =>
# k * (x2 - x1) = y2 - y1 =>
# k = (y2 - y1) / (x2 - x1) = dy / dx = const for the line
if len(coords) < 2:
return False
dx = coords[1][0] - coords[0][0]
dy = coords[1][1] - coords[0][1]
for i in range(2, len(coords)):
dx2 = coords[i][0] - coords[0][0]
dy2 = coords[i][1] - coords[0][1]
if abs(dy * dx2 - dx * dy2) > EPS:
return False
return True