Max Points on a Line (LeetCode 149): Solution and Explanation
Given distinct points on a plane, find the largest number that lie on one straight line. Fix each point as an anchor, group the later points by their exact direction from it, and the biggest group plus the anchor is a candidate answer.
Intuition
A line is fixed by two points, so the brute force tries every pair and counts how many other points fall on that line. That is O(n^3), and most of the work repeats: every line through a given point is examined again for each partner.
Fix one point A instead. Two other points B and C are on the same line through A exactly when they lie in the same direction from A (or exactly opposite directions). So if you group every other point by its direction from A, each group is one line through A, and its size tells you how many points that line holds.
The direction must be an exact hash key. A floating-point slope dy / dx can round two different slopes to the same value or one slope to two values, and vertical lines divide by zero. The reduced pair (dx / g, dy / g), where g = gcd(|dx|, |dy|), is exact. Opposite directions describe the same line, so make the sign canonical: dx positive, or dy positive when dx is 0.
Approach: Anchor point with a hash map of reduced directions
- If there are at most two points, return how many there are. They always share a line.
- For each anchor i, start an empty map from direction to count.
- For each later point j, compute dx and dy from i to j, divide both by their gcd, and flip both signs if dx < 0, or if dx = 0 and dy < 0.
- Increase the count for that direction and update
bestwith it. - Pairs with earlier points are skipped, because the line through i and an earlier point k was already counted when k was the anchor.
- Return
best + 1, adding the anchor itself to its largest group.
Step-by-step example
points = [[1,1],[2,2],[3,3]]
- There are three points, so the early return does not apply. best = 0.
- Anchor 0 at (1,1). Point (2,2) gives (1, 1), gcd 1, direction 1/1, count 1, best = 1.
- Point (3,3) gives (2, 2), gcd 2, direction 1/1 again, count 2, best = 2.
- Anchor 1 at (2,2). Point (3,3) gives direction 1/1 with count 1. best stays 2.
- Anchor 2 has no later points. Return best + 1 = 3.
Code: Python, Java, C++
1class Solution:
2 def maxPoints(self, points: List[List[int]]) -> int:
3 n = len(points)
4 if n <= 2:
5 return n
6 best = 0
7 for i in range(n):
8 slopes = defaultdict(int)
9 for j in range(i + 1, n):
10 dx = points[j][0] - points[i][0]
11 dy = points[j][1] - points[i][1]
12 g = math.gcd(dx, dy)
13 dx, dy = dx // g, dy // g
14 if dx < 0 or (dx == 0 and dy < 0):
15 dx, dy = -dx, -dy
16 slopes[(dx, dy)] += 1
17 best = max(best, slopes[(dx, dy)])
18 return best + 11class Solution {
2 public int maxPoints(int[][] points) {
3 int n = points.length;
4 if (n <= 2) {
5 return n;
6 }
7 int best = 0;
8 for (int i = 0; i < n; i++) {
9 Map<String, Integer> slopes = new HashMap<>();
10 for (int j = i + 1; j < n; j++) {
11 int dx = points[j][0] - points[i][0];
12 int dy = points[j][1] - points[i][1];
13 int g = gcd(dx, dy);
14 dx /= g;
15 dy /= g;
16 if (dx < 0 || (dx == 0 && dy < 0)) {
17 dx = -dx;
18 dy = -dy;
19 }
20 String key = dx + "/" + dy;
21 slopes.put(key, slopes.getOrDefault(key, 0) + 1);
22 best = Math.max(best, slopes.get(key));
23 }
24 }
25 return best + 1;
26 }
27
28 private int gcd(int a, int b) {
29 return b == 0 ? Math.abs(a) : gcd(b, a % b);
30 }
31}1class Solution {
2public:
3 int maxPoints(vector<vector<int>>& points) {
4 int n = points.size();
5 if (n <= 2) {
6 return n;
7 }
8 int best = 0;
9 for (int i = 0; i < n; i++) {
10 map<pair<int, int>, int> slopes;
11 for (int j = i + 1; j < n; j++) {
12 int dx = points[j][0] - points[i][0];
13 int dy = points[j][1] - points[i][1];
14 int g = gcdAbs(dx, dy);
15 dx /= g;
16 dy /= g;
17 if (dx < 0 || (dx == 0 && dy < 0)) {
18 dx = -dx;
19 dy = -dy;
20 }
21 int c = ++slopes[{dx, dy}];
22 best = max(best, c);
23 }
24 }
25 return best + 1;
26 }
27
28private:
29 int gcdAbs(int a, int b) {
30 return b == 0 ? abs(a) : gcdAbs(b, a % b);
31 }
32};Time and space complexity
O(n^2 log C)
There are n(n - 1) / 2 pairs, and each needs a gcd that takes O(log C) steps, where C is the coordinate range.
O(n)
The map for one anchor holds at most n - 1 directions, and it is rebuilt for each anchor.
Other approaches
Check every pair's line against every point (time O(n^3), space O(1))
For each pair (i, j), count the points k with a zero cross product (xj - xi)(yk - yi) - (yj - yi)(xk - xi). It uses only integer math and is easy to verify, but it is O(n^3), about 4.5 million cross products for 300 points.
Floating-point slope as the key (time O(n^2), space O(n))
Group by dy / dx with a special key for vertical lines. It is shorter, but two distinct slopes can round to the same double, and -0.0 versus 0.0 can split one horizontal line into two keys. The reduced integer pair avoids all of that.
Common mistakes
- Using a double slope as the key, which can merge different slopes or split equal ones.
- Not fixing the sign. (1, -2) and (-1, 2) describe the same line through the anchor and must map to one key.
- Forgetting the anchor itself. The map counts other points, so the answer is the largest count plus one.
- Returning 0 for a single point. One point still lies on a line, so the answer is 1.
Frequently asked questions
Why is it enough to pair the anchor with later points only?
Any line holding the maximum set of points contains a point with the smallest index in that set. When that point is the anchor, every other point on the line comes later, so the full line is counted then.
Could two different lines through the anchor share a key?
No. Lines through the same point are different exactly when their directions are different, and the reduced, sign-fixed pair is unique for each direction.
Do I need to handle duplicate points?
Not in this version: all points are distinct, so dx and dy are never both zero and the gcd is always positive. The older variant with duplicates needs a separate counter for points equal to the anchor.
Why not reset best for each anchor?
best tracks the overall maximum across all anchors, so it should keep growing. Only the slope map is rebuilt per anchor.