Max Points on a Line

HardMath · Geometry · Hash Map🧩 Math & GeometryLeetCode #149 ↗Updated

Problem

You are given points[i] = [x, y], a set of distinct points with integer coordinates in the plane. Return the largest number of these points that lie together on one straight line.
Input[[1,1],[2,2],[3,3]]Output3
Input[[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]Output4

1 ≤ n ≤ 300  ·  -104 ≤ x, y ≤ 104  ·  all points are unique

Try it yourself

Java
class Solution {
    public int maxPoints(int[][] points) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Fix an anchor point: every other point on a common line through it shares the same direction. Represent the direction exactly as a reduced fraction (dy, dx) (divide by gcd, normalise the sign) and count equal keys in a hash map — no floating-point slopes.
PatternMath & Geometry

Instinct Digits, factors, slopes or distances hide a formula - find the invariant, then guard against overflow, negatives and floating-point error.

Memory hack Mod peels, gcd reduces, squares compare - and long saves the day. Peel digits with %10, reduce slopes with gcd, compare squared distances.

Open the Math & Geometry guide →

Approaches

Brute ForceEvery Pair Defines a Line + Cross Product

Time O(n3)Space O(1)

Any line with ≥ 2 points is fixed by some pair (i, j). For each pair, count the points k that are collinear, using the integer cross product (xj-xi)(yk-yi) == (yj-yi)(xk-xi). No division, so no precision issues; products stay below 4·108, safe in int.

Java
public int maxPoints(int[][] points) {
    int n = points.length;
    if (n <= 2) return n;
    int best = 2;
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {
            int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];
            int count = 2;
            for (int k = j + 1; k < n; k++) {
                int ex = points[k][0] - points[i][0], ey = points[k][1] - points[i][1];
                if (dx * ey == dy * ex) count++;
            }
            best = Math.max(best, count);
        }
    return best;
}

Exact and simple, but ~4.5·106 pairs × 300 checks is slow.

At a glance

LevelApproachTimeSpace
Brute ForceEvery Pair Defines a Line + Cross ProductO(n3)O(1)
OptimalAnchor + Hash Map of Reduced SlopesO(n2 log C)O(n)
Common pitfalls
  • Using double slopes — precision errors, and 0.0 vs -0.0 keys differ.
  • Not normalising the sign: (1,-2) and (-1,2) are the same direction.
  • Forgetting vertical lines (dx = 0) or returning 0 for a single point.
Interview tips
  • Ask whether points can repeat — it changes the counting.
  • Justify the exact key: reduced fraction with a canonical sign is unique per direction.
  • Mention cross-product collinearity as the division-free alternative.
Pattern
Anchor + hash of canonical keys → group items relative to a pivot (slopes, differences) using exact, normalised keys.
My notes saved in this browser