Max Points on a Line
Hard
Topics
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
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.[x, y] points, plotted here on the grid they span.Input: grid = [[1,1],[2,2],[3,3]] Output: 3
Example 2
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
- Return
ndirectly when there are two or fewer points. - For each anchor, build a map from reduced direction to count.
- For each other point, reduce
(dx, dy)by their gcd and canonicalise the sign. - 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)isk, 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 != 0guard 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 bestimport java.util.*;
class Solution {
public int maxPoints(int[][] grid) {
int n = grid.length;
if (n <= 2) return n;
int best = 1;
for (int i = 0; i < n; i++) {
Map<String,Integer> slopes = new HashMap<>();
for (int j = 0; j < n; j++) {
if (i == j) continue;
int dx = grid[j][0] - grid[i][0], dy = grid[j][1] - grid[i][1];
int g = gcd(Math.abs(dx), Math.abs(dy));
if (g != 0) {
dx /= g;
dy /= g;
}
if (dx < 0 || (dx == 0 && dy < 0)) {
dx = -dx;
dy = -dy;
}
String key = dx + "," + dy;
int c = slopes.getOrDefault(key, 0) + 1;
slopes.put(key, c);
if (c + 1 > best) best = c + 1;
}
}
return best;
}
private int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxPoints(vector<vector<int>>& grid) {
int n = grid.size();
if (n <= 2) return n;
int best = 1;
for (int i = 0; i < n; i++) {
unordered_map<string,int> slopes;
for (int j = 0; j < n; j++) {
if (i == j) continue;
int dx = grid[j][0] - grid[i][0], dy = grid[j][1] - grid[i][1];
int ga = abs(dx), gb = abs(dy);
while (gb) {
int t = ga % gb;
ga = gb;
gb = t;
}
int g = ga;
if (g != 0) {
dx /= g;
dy /= g;
}
if (dx < 0 || (dx == 0 && dy < 0)) {
dx = -dx;
dy = -dy;
}
string key = to_string(dx) + "," + to_string(dy);
slopes[key]++;
if (slopes[key] + 1 > best) best = slopes[key] + 1;
}
}
return best;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var maxPoints = function(grid) {
const pts = grid, n = pts.length;
if (n <= 2) return n;
const gg = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b) {
const t = a % b;
a = b;
b = t;
}
return a;
};
let best = 1;
for (let i = 0; i < n; i++) {
const slopes = {};
for (let j = 0; j < n; j++) {
if (i === j) continue;
let dx = pts[j][0] - pts[i][0], dy = pts[j][1] - pts[i][1];
const g = gg(dx, dy);
if (g !== 0) {
dx = dx / g;
dy = dy / g;
}
if (dx < 0 || (dx === 0 && dy < 0)) {
dx = -dx;
dy = -dy;
}
const key = dx + ',' + dy;
slopes[key] = (slopes[key] || 0) + 1;
if (slopes[key] + 1 > best) best = slopes[key] + 1;
}
}
return best;
};