149. Max Points on a Line
Asked at 15Apple51Meta28Bloomberg28Google27Amazon22Microsoft20LinkedIn57Waymo100X94Zoox66Meesho57Sprinklr54Cisco51Citadel47Nvidia39
Problem
Given distinct points on a plane, return the largest number of them that lie on one straight line.
Example: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] → 4
Constraints: up to 300 points.
For each anchor point, group all other points by reduced slope (dy/g, dx/g) with a normalized sign. The largest group + 1 (the anchor) is the best line through that anchor.
Complexity: O(n²).
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
best = 1
for i, (x1, y1) in enumerate(points):
slopes = defaultdict(int)
for x2, y2 in points[i + 1:]:
dx, dy = x2 - x1, y2 - y1
g = math.gcd(dx, dy)
dx, dy = dx // g, dy // g
if dx < 0 or (dx == 0 and dy < 0):
dx, dy = -dx, -dy
slopes[(dx, dy)] += 1
best = max(best, slopes[(dx, dy)] + 1)
return best
assert Solution().maxPoints([[1, 1], [2, 2], [3, 3]]) == 3
assert Solution().maxPoints([[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]]) == 4
class Solution {
public int maxPoints(int[][] points) {
int best = 1;
for (int i = 0; i < points.length; i++) {
Map<String, Integer> slopes = new HashMap<>();
for (int j = i + 1; j < points.length; j++) {
int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];
int g = gcd(Math.abs(dx), Math.abs(dy));
dx /= g; dy /= g;
if (dx < 0 || (dx == 0 && dy < 0)) { dx = -dx; dy = -dy; }
best = Math.max(best, slopes.merge(dx + "/" + dy, 1, Integer::sum) + 1);
}
}
return best;
}
private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
func maxPoints(points [][]int) int {
best := 1
for i, p := range points {
slopes := map[[2]int]int{} // reduced direction -> points on that line through p
for _, q := range points[i+1:] {
dx, dy := q[0]-p[0], q[1]-p[1]
g := gcd(abs(dx), abs(dy))
dx, dy = dx/g, dy/g
if dx < 0 || dx == 0 && dy < 0 { // one sign convention per direction
dx, dy = -dx, -dy
}
key := [2]int{dx, dy}
slopes[key]++
best = max(best, slopes[key]+1)
}
}
return best
}
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}