Search⌘ K
AI Features

Solution: Check If It Is a Straight Line

Explore how to determine whether all given points lie on a single straight line in a 2D plane. Learn to calculate and compare slopes efficiently using cross-multiplication, avoiding division errors. This lesson helps you apply math and geometry patterns to solve this problem with time complexity O(n) and constant space.

Statement

You are given an array, coordinates, where each element in coordinates[i] =[x,y]= [x, y] represents the coordinates of a point on a 2D\text{2D} plane. Determine whether all the points in the array lie on a single straight line in the XY plane.

Constraints:

  • 22 \leq coordinates.length 1000\leq 1000

  • coordinates[i].length ==2== 2

  • 104-10^4 \leq coordinates[i][0]coordinates[i][1] 104\leq 10^4

  • coordinates do not contain any duplicate points.

Solution

We need to determine whether a given array of coordinates in a 2D\text{2D} plane lies in a single straight line. This problem is approached using the Math and Geometry pattern, using the slope of a straight line.

Key intuition:

The slope represents the change in y-coordinates\text{y-coordinates} relative to the change in x-coordinates\text{x-coordinates} for any two points on the line. So, the slope between two points,  ...