InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Max Points on a Line

hard Original ↗ 00:00

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 counts as 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 avoid floating-point error: 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug