LeetCode 1232: Check If It Is a Straight Line

link

Say the line has slope m. If a point’s slope with a point on the line is m, the new point is also on the line. For each pair of consecutive points we check if they have the same slope.

With n points, time: \mathcal{O}(n), space: \mathcal{O}(1).

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