#1232
Check If It Is a Straight Line
EasyArrayMathGeometryGeometryMathematical Properties
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking slopes for every point, we can use the concept of cross products to determine if points are collinear, which is more efficient.
⚙️
Algorithm
3 steps- 1Step 1: If there are only 2 points, return true.
- 2Step 2: Calculate the differences dx1 = x2 - x1 and dy1 = y2 - y1 for the first two points.
- 3Step 3: For each subsequent point, calculate dx2 = x - x1 and dy2 = y - y1, and check if dx1 * dy2 == dy1 * dx2.
solution.py12 lines
1# Full working Python code
2
3def checkStraightLine(coordinates):
4 if len(coordinates) == 2:
5 return True
6 (x1, y1), (x2, y2) = coordinates[0], coordinates[1]
7 dx1, dy1 = x2 - x1, y2 - y1
8 for x, y in coordinates[2:]:
9 dx2, dy2 = x - x1, y - y1
10 if dx1 * dy2 != dy1 * dx2:
11 return False
12 return Trueℹ
Complexity note: This complexity is linear because we only traverse the list of coordinates once, checking the condition for each point.
- 1Two points define a line.
- 2Collinearity can be checked using cross products.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.