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 It Is a Straight Line INPUT X Y (1,2) (2,3) (3,4) coordinates = [ [1,2], [2,3], [3,4] ] ALGORITHM STEPS 1 Get First Two Points P0=(1,2), P1=(2,3) 2 Calculate Base Diff dx=2-1=1, dy=3-2=1 3 Cross Multiply Check For each point Pi: dx_i = x[i] - x[0] dy_i = y[i] - y[0] dy*dx_i == dx*dy_i ? 4 Verify Point (3,4) dx_i=2, dy_i=2 1*2 == 1*2 --> OK All points satisfy: dy * dx_i == dx * dy_i FINAL RESULT P0 P1 P2 All Points Collinear Output: true Points form a straight line! Key Insight: Cross multiplication avoids division by zero! Instead of comparing slopes (dy1/dx1 = dy2/dx2), we compare cross products (dy1 * dx2 = dx1 * dy2). This handles vertical lines and is more precise with integers. Time: O(n), Space: O(1) - single pass through all points! TutorialsPoint - Check If It Is a Straight Line | Optimized - Single Pass with Cross Multiplication
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