Check If It Is a Straight Line — LeetCode 1232 Python Solution
- Problem
- #1232
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
- Output
- true
Python solution
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
for x, y in coordinates[2:]:
if (x - x1) * (y2 - y1) != (y - y1) * (x2 - x1):
return False
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the `coordinates` array |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1232. Check If It Is a Straight Line is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Geometry.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1232. Check If It Is a Straight Line?
- LeetCode 1232. Check If It Is a Straight Line is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1232. Check If It Is a Straight Line?
- The Python solution on this page runs in O(n), where n is the length of the `coordinates` array.
- What is the space complexity of LeetCode 1232. Check If It Is a Straight Line?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1232. Check If It Is a Straight Line cover?
- LeetCode 1232. Check If It Is a Straight Line is tagged Geometry, Array and Math on LeetCode.