1232. Check If It Is a Straight Line
easyDecide whether a list of 2D points lies on a single straight line. The clean answer avoids floating-point slope division and uses cross-product equality instead.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given an 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.
Constraints
2 <= coordinates.length <= 1000coordinates[i].length == 2-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4coordinates contains no duplicate point.
Examples
Example 1
coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]trueExample 2
coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]falseSolve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Two points always make a line, so 2 coordinates -> return true.
Hint 2
Naive: compare the slope between consecutive points. But division by zero (vertical lines) and floating-point error make this fragile.
Hint 3
Better: use cross-product. The vector from p0 to p1 is (dx, dy). For any subsequent point pi, the vector (dxi, dyi) is collinear iff dx * dyi - dy * dxi == 0.
Hint 4
Walk every point i >= 2 and apply that integer cross-product check. All zeroes -> collinear.
Solution approach
Reveal approach
Compute the reference vector dx = x1 - x0, dy = y1 - y0 from the first two points. For every subsequent point (xi, yi), compute dxi = xi - x0, dyi = yi - y0 and check the cross product: dx * dyi - dy * dxi == 0. Return false on the first non-zero result; return true after all points pass. The integer cross product avoids any division and any floating-point comparison. O(n) time, O(1) space. With n == 2 the loop runs zero iterations and we return true correctly. The single zero-product check is more robust than slope-comparison both for vertical lines and for floating-point precision.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- math
- geometry
Related problems
- 149. Max Points on a Line
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
Practice these live with InterviewChamp.AI
Drill Check If It Is a Straight Line and Math problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →