Use cross multiplication to compare each point's displacement with the first segment, avoiding division and vertical-line special cases.
Complexity
O(n) time and O(1) space.
Determine whether every coordinate lies on one straight line.
Use cross multiplication to compare each point's displacement with the first segment, avoiding division and vertical-line special cases.
O(n) time and O(1) space.
package main
func checkStraightLine(coordinates [][]int) bool {
dx, dy := coordinates[1][0]-coordinates[0][0], coordinates[1][1]-coordinates[0][1]
for _, point := range coordinates[2:] {
if (point[0]-coordinates[0][0])*dy != (point[1]-coordinates[0][1])*dx {
return false
}
}
return true
}
class Solution:
def checkStraightLine(self, coordinates: list[list[int]]) -> bool:
dx = coordinates[1][0] - coordinates[0][0]; dy = coordinates[1][1] - coordinates[0][1]
return all((x - coordinates[0][0]) * dy == (y - coordinates[0][1]) * dx for x, y in coordinates[2:])
function checkStraightLine(coordinates: number[][]): boolean {
const dx = coordinates[1][0] - coordinates[0][0]; const dy = coordinates[1][1] - coordinates[0][1];
return coordinates.slice(2).every(([x, y]) => (x - coordinates[0][0]) * dy === (y - coordinates[0][1]) * dx);
}