Check If It Is a Straight Line

All points lie on one line iff every point shares the cross-product direction with the first edge.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
geometry math cross-product

Problem#

Return true iff all given 2D points lie on a single straight line.

Examples#

  • [[1,2],[2,3],[3,4],[4,5]]true.
  • [[1,1],[2,2],[3,4]]false.

Constraints#

  • 2 <= coordinates.length <= 1000.

Approach#

Fix the first two points as the reference edge. For each later point, check the cross product of (p1 → p2) and (p1 → pk) is zero.

Solution#

Check If It Is a Straight Line
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& c) {
long long dx = c[1][0] - c[0][0], dy = c[1][1] - c[0][1];
for (int i = 2; i < (int)c.size(); ++i) {
long long ex = c[i][0] - c[0][0], ey = c[i][1] - c[0][1];
if (dx * ey - dy * ex != 0) return false;
}
return true;
}
};

Editorial#

Cross product is the right tool — it sidesteps division-by-zero for vertical lines and gives an exact integer answer for integer inputs.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.