CodingNodes / Math & Geometry / Max Points on a Line System design Space play · ←→ step · R restart

Problem

You are given points, a list of distinct points [x, y] on a flat plane. A set of points is on a line when one straight line passes through all of them.

Return the largest number of points that lie on a single straight line. Lines may be horizontal, vertical or slanted.

Constraints

  • 1 ≤ points.length ≤ 300
  • −10⁴ ≤ x, y ≤ 10⁴
  • All points are distinct

Examples: pick one to animate

Solutions

TimeO(n²) SpaceO(n)

Time: Every pair of points is looked at once, and each step is a gcd plus a map update.

Space: For one anchor the map holds at most n - 1 directions, and it is rebuilt for each anchor.

Fix one point as an anchor. Every other point lies in some direction (dx, dy) from it, and two points are on one line with the anchor exactly when they share a direction. Divide dx and dy by their gcd and fix the sign so equal directions give equal pairs. That avoids dividing (no slope rounding errors, no division by zero for vertical lines). The biggest bucket plus the anchor itself is the best line through that anchor.