Max Points on a Line

Hard

Topics
ArrayHash TableMathGeometry

You are given grid, where each row is a distinct point [x, y] on the plane. Return the maximum number of points that lie on the same straight line.

Example 1

···●··●··●······
the best line
Points plotted with y upward. The shaded ones are collinear, so the answer is 3. Collinearity has to be tested by cross product rather than by slope, because a vertical line has no slope and floating-point slopes collide.
Input is a list of [x, y] points, plotted here on the grid they span.
Input:  grid = [[1,1],[2,2],[3,3]]
Output: 3

Example 2

·●······●··●···●···●··●·······
the best lineother points
Input:  grid = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4

Constraints

  • 1 <= grid.length <= 300
  • grid[i].length == 2
  • all points are distinct
Editorial — intuition, approach, complexity and pitfalls

Intuition

Any line through two points is determined by their direction, so fix one point as an anchor and group the others by the direction from it. The largest group, plus the anchor itself, is the best line through that anchor. Repeat for every anchor.

The whole difficulty is making "same direction" an exact equality test. Floating-point slope dy/dx fails twice over: it divides by zero for vertical lines, and it conflates directions that differ in the last bits. Instead reduce (dx, dy) by their greatest common divisor and then fix the sign so that each direction has exactly one representation. The shown code normalises to dx > 0, or dx == 0 with dy > 0.

Approach

  1. Return n directly when there are two or fewer points.
  2. For each anchor, build a map from reduced direction to count.
  3. For each other point, reduce (dx, dy) by their gcd and canonicalise the sign.
  4. Track the best count plus one for the anchor.

Dry Run

points = [[0,0],[0,1],[0,5],[3,3]]

anchor (0,0)
  to (0,1)  d = (0,1)   gcd 1, already canonical    -> key (0,1)
  to (0,5)  d = (0,5)   gcd 5 -> (0,1)              -> key (0,1)  count 2
  to (3,3)  d = (3,3)   gcd 3 -> (1,1)              -> key (1,1)  count 1

best group is (0,1) with 2, plus the anchor  ->  3

answer 3   the vertical line x = 0 holds three points

sign canonicalisation matters: from (0,5) back to (0,0) the delta is (0,-5),
which reduces to (0,-1). Negating it to (0,1) is what makes the two directions
compare equal.

Complexity

  • Time — O(n²): every ordered pair is examined once, with a gcd that is O(log(coordinate)) and effectively constant here. At the stated bound of 300 points that is 90,000 pairs.
  • Space — O(n) for one anchor's direction map, rebuilt per anchor.

Common Pitfalls

  • Using floating-point slope. Vertical lines divide by zero, and two genuinely collinear directions can hash to different doubles. The reduced integer pair is exact.
  • Reducing by the gcd but skipping the sign normalisation, so (1,2) and (-1,-2) are treated as different directions and every line is counted twice at half strength.
  • Forgetting that gcd(0, k) is k, so a vertical delta (0, 5) must still reduce to (0, 1).
  • Handling duplicate points. This problem's statement promises distinct points, which is why the g != 0 guard is only defensive; the general version needs a separate duplicate count added to every group.
  • Returning the largest group without adding the anchor, which undercounts every line by one.
  • Starting the answer at 0 rather than 1. A single point is a line of one.

Full Solution — all languages

class Solution:
    def maxPoints(self, grid):
        import math
        pts = grid
        n = len(pts)
        if n <= 2:
            return n
        best = 1
        for i in range(n):
            slopes = {}
            for j in range(n):
                if i == j:
                    continue
                dx = pts[j][0] - pts[i][0]
                dy = pts[j][1] - pts[i][1]
                g = math.gcd(dx, dy)
                if g != 0:
                    dx //= g
                    dy //= g
                if dx < 0 or (dx == 0 and dy < 0):
                    dx, dy = -dx, -dy
                key = (dx, dy)
                slopes[key] = slopes.get(key, 0) + 1
                if slopes[key] + 1 > best:
                    best = slopes[key] + 1
        return best
SensAI
Beta
Tap the mic to stop voice mode