Check If It Is a Straight Line
LeetCode 1349 | Difficulty: Easyβ
EasyProblem Descriptionβ
You are given an integer array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
Constraints:
- `2 <= coordinates.length <= 1000`
- `coordinates[i].length == 2`
- `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
- `coordinates` contains no duplicate point.
Topics: Array, Math, Geometry
Approachβ
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
When to use
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 96 ms)β
| Metric | Value |
|---|---|
| Runtime | 96 ms |
| Memory | 40.6 MB |
| Date | 2022-01-17 |
Solution
public class Solution {
public bool CheckStraightLine(int[][] coordinates) {
if(coordinates.Length < 2) return false;
var p = coordinates[0];
var q = coordinates[1];
for(int i=2;i<coordinates.Length;i++)
{
var curr = coordinates[i];
if((curr[0]-p[0])*(q[1]-p[1]) != (curr[1]-p[1]) * (q[0] - p[0])) return false;
}
return true;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 3 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: If there're only 2 points, return true.
Hint 2: Check if all other points lie on the line defined by the first 2 points.
Hint 3: Use cross product to check collinearity.