Check If It Is a Straight Line - Problem
Check If Points Form a Straight Line

You are given an array of coordinates where each coordinate is represented as [x, y]. Your task is to determine whether all these points lie on a single straight line in the XY plane.

Goal: Return true if all points are collinear (lie on the same straight line), otherwise return false.

Key Insight: Three or more points are collinear if the slope between any two pairs of points is the same. However, we need to handle the special case of vertical lines where the slope is undefined.

Example: Points [[1,2],[2,3],[3,4]] all lie on the line y = x + 1, so they form a straight line.

Input & Output

example_1.py — Basic Straight Line
$ Input: coordinates = [[1,2],[2,3],[3,4]]
Output: true
💡 Note: All points lie on the line y = x + 1. The slope between any two consecutive points is 1, confirming they are collinear.
example_2.py — Not a Straight Line
$ Input: coordinates = [[1,1],[2,2],[3,4]]
Output: false
💡 Note: The slope between points (1,1) and (2,2) is 1, but the slope between (2,2) and (3,4) is 2. Since slopes are different, points don't form a straight line.
example_3.py — Vertical Line
$ Input: coordinates = [[2,1],[2,3],[2,5]]
Output: true
💡 Note: All points have the same x-coordinate (x = 2), forming a perfect vertical line. This is handled correctly by the cross product method.

Visualization

Tap to expand
Cross Product Collinearity CheckABCDCheck if D is collinearCross Product ResultPoints A, B, C: Cross product = 0 ✓Points A, B, D: Cross product ≠ 0 ✗Conclusion: A, B, C are collinear, but D is not on the same line
Understanding the Visualization
1
Set Reference Line
Use the first two points to establish our reference line direction
2
Apply Cross Product
For each additional point, calculate the cross product with reference points
3
Check Result
If cross product is zero, the point is collinear; otherwise, it's not on the line
4
Conclusion
All points are collinear only if all cross products equal zero
Key Takeaway
🎯 Key Insight: Cross product elegantly solves the collinearity problem without division, handling all edge cases including vertical lines naturally while maintaining O(n) time complexity.

Time & Space Complexity

Time Complexity
⏱️
O(n)

We iterate through each point once after establishing the reference line

n
2n
Linear Growth
Space Complexity
O(1)

Only using constant extra space for calculations

n
2n
Linear Space

Constraints

  • 2 ≤ coordinates.length ≤ 1000
  • coordinates[i].length == 2
  • -104 ≤ coordinates[i][0], coordinates[i][1] ≤ 104
  • No two coordinates are the same
Asked in
Google 25 Amazon 18 Apple 12 Microsoft 8
78.9K Views
Medium Frequency
~15 min Avg. Time
1.8K 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