Max Points on a Line

For each anchor, hash slopes in reduced (dx, dy) form — most popular slope gives the line through this anchor.

Hard
Time O(n^2) Space O(n)
LeetCode
6 min read
geometry hash-map math gcd

Problem#

Return the maximum number of points that lie on the same straight line.

Examples#

  • [[1,1],[2,2],[3,3]]3.
  • [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]4.

Constraints#

  • 1 <= points.length <= 300.

Approach#

For each anchor i, hash the slope to every other point as a normalized (dx, dy) pair (divide by gcd, force canonical sign). The maximum bucket size plus 1 (for the anchor) is a candidate; take the max across anchors.

Solution#

Max Points on a Line
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int n = points.size();
if (n <= 2) return n;
int ans = 1;
for (int i = 0; i < n; ++i) {
unordered_map<long long, int> mp;
int local = 0;
for (int j = 0; j < n; ++j) {
if (i == j) continue;
int dx = points[j][0] - points[i][0];
int dy = points[j][1] - points[i][1];
int g = __gcd(abs(dx), abs(dy));
if (g == 0) g = 1;
dx /= g; dy /= g;
if (dx < 0 || (dx == 0 && dy < 0)) { dx = -dx; dy = -dy; }
long long key = ((long long)dx << 20) ^ ((long long)(unsigned)dy);
local = max(local, ++mp[key]);
}
ans = max(ans, local + 1);
}
return ans;
}
};

Editorial#

Using gcd-normalized (dx, dy) instead of slope as a float avoids precision issues; the canonical-sign step ensures (2,4) and (-2,-4) hash to the same key. Anchor-and-rest is O(n^2) total — within the n <= 300 budget.

Complexity#

  • Time: O(n^2) (gcd is effectively O(log max)).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.