LeetCode #149 Hard

Max Points on a Line

Max Points on a Line is LeetCode 149 (Hard). Each points[i] = [x, y] is a point on a plane. Return the largest number of points that lie on one straight line.

  • There are at most 300 points, all different, with whole-number coordinates between −10⁴ and 10⁴.
  • 300 points make about 45,000 pairs, so an O(n²) pass over every pair is cheap.
Constraints
  • 1 <= points.length <= 300
  • points[i].length == 2
  • -10⁴ <= xi, yi <= 10⁴
  • All the points are unique.
arrayhash-tablegeometry
Open on LeetCode ↗
02

Intuition

A line is fixed by one point on it and a direction. So fix one point as the anchor and group every other point by its direction from it. Points in one group lie on one line through the anchor, and the biggest group plus the anchor is the best line through it. Trying every point as the anchor covers every line.

The direction must be an exact key:

  • Reduce: divide dx and dy by their greatest common divisor, so (2, 4) and (1, 2) match.
  • Fix the sign: make dx positive, or dy positive when dx is 0, so (−1, −2), on the far side of the anchor, matches (1, 2).
How to spot this pattern

When a question counts points on the same line, or on any shape fixed by one point and a direction, anchor one point and hash what the others look like from it. Keep the key in whole numbers so equal shapes always hash the same.

03

Approach

Try it first

Before reading on, decide what you would store about each point as seen from one fixed point, so that points on one line through it get the same key. Watch out for vertical lines and for points on opposite sides. Aim for O(n²) pairs.

1

Pick each point as the anchor

Loop i over the points and start a fresh, empty map for each one. A direction only means something relative to one anchor, so keys from an earlier anchor would merge lines that merely run parallel.

2

Pair it only with later points

Compare the anchor with points j > i. Any line is found in full when its earliest point is the anchor, because every other point on it comes later in the list.

3

Reduce the direction

Set dx = x2 − x1 and dy = y2 − y1, then divide both by gcd(dx, dy). A point twice as far along the same line gives (2, 4) instead of (1, 2), and dividing by the gcd turns both into (1, 2). Points are distinct, so the gcd is never 0.

4

Make the sign unique

If dx < 0, or dx == 0 and dy < 0, flip both signs. A point on the other side of the anchor points the opposite way along the same line, and the flip puts it in the same group.

5

Count the group and update the answer

Add 1 to the group for this key. The line holds that many points plus the anchor itself, so compare count + 1 with the best so far.

04

Code in Python, C++ and Java

▶1from collections import defaultdict
▶2from math import gcd
▶3 
▶4class Solution:
▶5 def maxPoints(self, points):
▶6 best = 1
▶7 for i, (x1, y1) in enumerate(points):
▶8 lines = defaultdict(int)
▶9 for x2, y2 in points[i + 1:]:
▶10 dx, dy = x2 - x1, y2 - y1
▶11 g = gcd(dx, dy)
▶12 dx, dy = dx // g, dy // g
▶13 if dx < 0 or (dx == 0 and dy < 0):
▶14 dx, dy = -dx, -dy
▶15 lines[(dx, dy)] += 1
▶16 best = max(best, lines[(dx, dy)] + 1)
▶17 return best
123123pointsdirectionsthis pairbest13 points, best starts at 1
points3
best1one point is a line of one
Each point will take a turn as the anchor. From the anchor, every later point gets a direction key, and points with the same key share a line through the anchor. The answer starts at 1, because even a single point counts.
123123pointsdirectionsempty mapthis pairbest1anchor (1, 1) → new empty map
anchor(1, 1)point 0
later points2
Anchor at (1, 1) with an empty map. Only points after it in the list are checked; a line is always found when its earliest point is the anchor.
123123pointsdirections(1, 1)→1this pair(1, 1)÷1(1, 1)best2point (2, 2) → key (1, 1), 2 on this line
dx, dy(1, 1)from the anchor
key(1, 1)gcd is 1
best2
From the anchor, (2, 2) is (1, 1) away. It starts a new group: 1 point plus the anchor = 2. That beats the best so far.
123123pointsdirections(1, 1)→2this pair(2, 2)÷2(1, 1)best3point (3, 3) → key (1, 1), 3 on this line
dx, dy(2, 2)from the anchor
key(1, 1)divided by gcd 2
best3
From the anchor, (3, 3) is (2, 2) away. Dividing by the gcd 2 gives (1, 1), the smallest whole-number step in that direction, so every point on this line gets the same key. That key already had 1 point, so this line now holds 2 points plus the anchor = 3. That beats the best so far.
123123pointsdirectionsempty mapthis pairbest3anchor (2, 2) → new empty map
anchor(2, 2)point 1
later points1
Move the anchor to (2, 2) and clear the map. Directions from the old anchor describe different lines, so they must not mix with these. Earlier points are greyed out: every line through them was already counted.
123123pointsdirections(1, 1)→1this pair(1, 1)÷1(1, 1)best3point (3, 3) → key (1, 1), 2 on this line
dx, dy(1, 1)from the anchor
key(1, 1)gcd is 1
best3
From the anchor, (3, 3) is (1, 1) away. It starts a new group: 1 point plus the anchor = 2.
123123pointsdirectionsthis pairbest3best line holds 3 points → return 3
result3
The last point has no later points to pair with, so the loop ends. The best line goes through (1, 1), (2, 2), (3, 3), so the answer is 3. Only whole numbers were ever compared, so no rounding could merge or split a line.
05

Common pitfalls

Using a floating-point slope as the key

✗ Wrong
key = dy / dx
✓ Right
g = gcd(dx, dy)
key = (dx // g, dy // g)  # then fix the sign

In Python a vertical pair divides by zero and crashes. In C++ and Java, 1.0 / 0 and -1.0 / 0 give +inf and -inf, so [[0,0],[0,1],[0,-1]] splits the vertical line and returns 2 instead of 3. Java's Double keys also treat 0.0 and -0.0 as different, which splits a horizontal line the same way.

Skipping the sign fix

✗ Wrong
key = (dx // g, dy // g)
✓ Right
if dx < 0 or (dx == 0 and dy < 0):
    dx, dy = -dx, -dy
key = (dx, dy)

On [[0,0],[1,2],[-1,-2]], the anchor (0, 0) files (1, 2) and (−1, −2) under two different keys. Each group has one point, and the answer comes out 2 instead of 3.

06

Edge cases

Only one point

No pair is ever checked, so the answer must start at 1, not 0. One point is a line of one.

A vertical or horizontal line

A vertical pair has dx = 0; the gcd is |dy|, so it reduces to (0, 1) or (0, −1), and the sign fix makes both (0, 1). A horizontal pair reduces to (1, 0) or (−1, 0) and becomes (1, 0). No special case is needed.

07

Complexity

Time
O(n² log C)
Space
O(n)
n is the number of points and C the largest coordinate difference, 2 × 10⁴. Each of the n(n − 1)/2 pairs costs one gcd, which takes O(log C) steps. One anchor's map holds at most n − 1 keys.
08

Max Points on a Line FAQ

What if the points can repeat?

This version promises distinct points, but some variants do not. A copy of the anchor has dx = dy = 0, which has no direction and makes the gcd 0. Count those copies separately and add the count to the anchor's best group, since a copy lies on every line through the anchor.

Why not check every pair against every other point?

Three collinear points satisfy (y2 − y1)(x3 − x1) == (y3 − y1)(x2 − x1), a test with no division at all. Trying it for every pair and every third point is O(n³): about 13 million checks for 300 points. That still passes here, but the anchor-and-map method is O(n²) and scales further.

Can I use the angle or a string as the key?

An angle from atan2 is a float, so it has the rounding and signed-zero trouble of a float slope. A string such as "1,2" built from the reduced, sign-fixed pair works fine; it is just slower to build than a tuple or pair.