Skip to main content

Check If It Is a Straight Line

LeetCode 1349 | Difficulty: Easy​

Easy

Problem 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)​

MetricValue
Runtime96 ms
Memory40.6 MB
Date2022-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​

ApproachTimeSpace
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.