Check If It Is a Straight Line — LeetCode 1232 Python Solution

EasyGeometryArrayMath
Problem
#1232
Reading time
2 min

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

Python
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 True

Complexity

MeasureComplexity
TimeO(n), where n is the length of the `coordinates` array
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview