Skip to content

1232. Check If It Is a Straight Line

View on LeetCode

Approach: For each later point, check collinearity with the first segment via cross-product equality.

Complexity: O(n) time, O(1) space

js
/**
 * @param {number[][]} coordinates
 * @return {boolean}
 */
var checkStraightLine = function(coordinates) {
    if (coordinates.length <= 2) {
        return true
    }
    for (let i = 2; i< coordinates.length; i++) {
        const a = (coordinates[i][1] - coordinates[0][1]) * (coordinates[1][0] - coordinates[0][0])
        const b = (coordinates[1][1] - coordinates[0][1]) * (coordinates[i][0] - coordinates[0][0])
        if (a !== b) {
            return false
        }
    }
    return true
};