Check If It Is a Straight Line - Problem

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

Note: A straight line requires at least 2 points. All points must lie on the same infinite line.

Approach: Use the slope formula to check if all points have the same slope relative to the first two points. To avoid division by zero, use cross multiplication: (y2-y1) * (x3-x1) = (y3-y1) * (x2-x1)

Input & Output

Example 1 — Basic Straight Line
$ Input: coordinates = [[1,2],[2,3],[3,4]]
Output: true
💡 Note: All points lie on the line y = x + 1. Slope between any two points is 1.
Example 2 — Not a Straight Line
$ Input: coordinates = [[1,1],[2,2],[3,4]]
Output: false
💡 Note: Points (1,1) and (2,2) have slope 1, but (2,2) and (3,4) have slope 2. Different slopes mean not a straight line.
Example 3 — Minimum Case
$ Input: coordinates = [[0,0],[1,1]]
Output: true
💡 Note: Only two points - they always form a straight line by definition.

Constraints

  • 2 ≤ coordinates.length ≤ 1000
  • coordinates[i].length == 2
  • -104 ≤ coordinates[i][0], coordinates[i][1] ≤ 104
  • coordinates contains no duplicate points

Visualization

Tap to expand
Check If Points Form Straight LineInput: Coordinates[[1,2],[2,3],[3,4]]Visualization(1,2)(2,3)(3,4)slope = 1Algorithm1. Take first 2 points2. Check remaining points3. Use cross multiplication(y2-y1)×(x3-x1) = (y3-y1)×(x2-x1)Output: trueAll points lie on the same straight line
Understanding the Visualization
1
Input
Array of 2D coordinates [[x1,y1], [x2,y2], ...]
2
Process
Check if all points have same slope using cross multiplication
3
Output
Return true if collinear, false otherwise
Key Takeaway
🎯 Key Insight: Use cross multiplication to compare slopes without division, avoiding floating point precision issues
Asked in
Amazon 15 Google 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen