InterviewPrepKit

Home / Coding / Math & Geometry

Max Points on a Line

hard Original β†—
Solving tips
  • Fix each point as an anchor and hash the slope to every other point; the largest bucket plus the anchor itself is the best line through it.
  • Represent slope EXACTLY as a reduced integer pair (dy//g, dx//g) with g = gcd(dx, dy); never compare floating dy/dx.
  • Pin a sign convention (e.g. force dx > 0) so opposite directions along the same line share one key, and give vertical/horizontal lines sentinel keys.
  • Remember the +1 for the anchor and special-case n <= 2; target O(n^2) time, O(n) space.

Problem

You are given points, a list of [x, y] coordinates on the 2-D plane. Return the maximum number of points that all lie on the same straight line.

Any two points define a line; the question is how many of the given points can share one line simultaneously.

Examples

  • points = [[1,1],[2,2],[3,3]] β†’ 3 β€” all three lie on the line y = x.
  • points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] β†’ 4 β€” the four points [1,4],[2,3],[3,2],[4,1] all satisfy x + y = 5, so they share one line.
  • points = [[0,0]] β†’ 1 β€” a single point trivially forms a β€œline” of size 1.

Constraints

  • 1 <= len(points) <= 300
  • -10^4 <= x, y <= 10^4
  • All points are distinct.
  • With n <= 300, an O(nΒ²) or O(nΒ² log n) solution is comfortably fast; the challenge is comparing slopes exactly, without floating-point error.

Think about it first

Hint 1 Three points are collinear iff each pair shares the same slope. Fix one point as an anchor; every other point has some slope relative to it, and points on one line through the anchor all share that slope.
Hint 2 For each anchor point, hash the slope to every other point and count how many points give each slope. The largest bucket (plus the anchor itself) is the best line through that anchor. Repeat over all anchors.
Hint 3 Represent a slope exactly to dodge floating-point trouble: use the reduced fraction `(dy, dx)` divided by their `gcd`, with a fixed sign convention (e.g. keep `dx >= 0`, and normalize vertical/horizontal cases). Never compare raw `dy/dx` floats.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.