Skip to content

#1232EasyGeometry

Check If It Is a Straight Line

View on LeetCode ↗

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:

  1. Let dx = x1 − x0, dy = y1 − y0 from the first two points.
  2. For every later point (x, y), require (x − x0)·dy == (y − y0)·dx.
  3. Any mismatch → false immediately; 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 - x0
5 val dy = y1 - y0
6 for (i in 2 until points.size) {
7 val (x, y) = points[i]
8 if ((x - x0) * dy != (y - y0) * dx) return false
9 }
10 return true
11}

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

Recognize the window, and these fall to the same skeleton.