#1232EasyGeometry
Check If It Is a Straight Line
Start dumb: compare slopes
“On the same line” means “same slope from a fixed point.” So compute the
slope from point 0 to point 1, then check every other point has that slope
from point 0. The idea is right, but dy / dx invites two bugs at once:
division by zero on a vertical line (dx == 0), and floating-point
rounding that makes two genuinely-equal slopes compare unequal. Both are
avoidable — the division is the problem.
Find the bottleneck
The only reason to divide is to turn two ratios into numbers you can compare. But you can compare the ratios without ever forming them.
The optimal shape
One pass after fixing the direction once:
- Let
dx = x1 − x0,dy = y1 − y0from the first two points. - For every later point
(x, y), require(x − x0)·dy == (y − y0)·dx. - Any mismatch →
falseimmediately; survive them all →true.
O(n) time, O(1) space, and it never divides — vertical lines and huge coordinates are handled by the same integer expression. In the player, the two anchors stay highlighted as the line-defining window; each tested point lights up, then turns green when it checks out, or red the instant one doesn’t.
Watch it think
Run the default straight diagonal, then the bent 1,1 2,2 3,4 (the third
point breaks it — watch it turn red), and the vertical 0,0 0,1 0,2 that a
slope-division solution would crash on.
Re-traces as you type — points as "x,y" separated by spaces (at least 2, coords within ±99); try the bent "1,1 2,2 3,4" or a vertical "0,0 0,1 0,2". Capped at 32 characters so the tiles stay readable.
Step 1 of 6: The first two points pin down one line, and its direction is (dx, dy) = (1, 1) — every remaining point must lie along that same direction. Variables: A = (1,2), B = (2,3), dx = 1, dy = 1.
Data
Code
1fun checkStraightLine(points: Array<IntArray>): Boolean {2 val (x0, y0) = points[0]3 val (x1, y1) = points[1]4 val dx = x1 - x05 val dy = y1 - y06 for (i in 2 until points.size) {7 val (x, y) = points[i]8 if ((x - x0) * dy != (y - y0) * dx) return false9 }10 return true11}
State
- A
- (1,2)
- B
- (2,3)
- dx
- 1
- dy
- 1
Why this step
The first two points pin down one line, and its direction is (dx, dy) = (1, 1) — every remaining point must lie along that same direction.
1 / 6
The same pattern also solves
Recognize the window, and these fall to the same skeleton.
- Minimum Time Visiting All Points (LC 1266)
Chebyshev distance between consecutive points — the same "reason about x and y deltas" style, no slopes needed.
- Max Points on a Line (LC 149)
The hard generalization — instead of one fixed line, find the line through the most points, grouping by slope.
- Valid Boomerang (LC 1037)
The exact opposite test on three points — a boomerang is valid only when they are NOT collinear (cross product ≠ 0).
- Convex Polygon (LC 469)
Cross products again, but tracking their sign around the vertices to decide convexity.