1232. Check if It Is a Straight Line

1232. Check If It Is a Straight Line #

Problem #

You are given an array coordinatescoordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

Constraints:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate point.

Problem Summary #

There are some points in an XY coordinate system. We use the array coordinates to record their coordinates respectively, where coordinates[i] = [x, y] represents the point whose x-coordinate is x and y-coordinate is y.

Please determine whether these points are on the same straight line in this coordinate system. If so, return true; otherwise, return false.

Notes:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate points

Solution Approach #

  • Given a set of coordinate points, determine whether these points are on the same straight line.
  • According to geometric principles, simply calculate whether the slopes of these points are equal in order. Computing the slope requires division; here, a trick is used to convert it to multiplication. For example, a/b = c/d changed to multiplication is a*d = c*d .

Code #


package leetcode

func checkStraightLine(coordinates [][]int) bool {
	dx0 := coordinates[1][0] - coordinates[0][0]
	dy0 := coordinates[1][1] - coordinates[0][1]
	for i := 1; i < len(coordinates)-1; i++ {
		dx := coordinates[i+1][0] - coordinates[i][0]
		dy := coordinates[i+1][1] - coordinates[i][1]
		if dy*dx0 != dy0*dx { // check cross product
			return false
		}
	}
	return true
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文