Algo-Sim › Math & Geometry

Max Points on a Line

Hard · Math & Geometry · step through it in Java, Python and C++ on your own input

Most points on one straight line: for each anchor, group the later points by reduced (dy, dx) direction in a hash map.

Problem

Given an array of distinct points where points[i] = [x, y], return the maximum number of points that lie on the same straight line.

Constraints

Edge cases to test

Follow-up questions

Why reduce (dy, dx) by the gcd instead of using the slope?
Floating-point slopes can round differently for the same line; reduced integer pairs with a fixed sign are exact.
Can it be faster than O(n²)?
Not for exact answers in general. If most points lie on one line, random pairs find it with high probability (as in RANSAC).

Solution

Java

public int maxPoints(int[][] points) {
    int n = points.length, best = 1;
    for (int i = 0; i < n; i++) {
        Map<String, Integer> slopes = new HashMap<>();
        for (int j = i + 1; j < n; j++) {
            int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];
            int g = gcd(dx, dy);
            dx /= g; dy /= g;
            // One sign per direction: dx > 0, or dx = 0 and dy > 0.
            if (dx < 0 || (dx == 0 && dy < 0)) { dx = -dx; dy = -dy; }
            int count = slopes.merge(dy + "/" + dx, 1, Integer::sum);
            best = Math.max(best, count + 1);
        }
    }
    return best;
}

int gcd(int a, int b) {
    return b == 0 ? Math.abs(a) : gcd(b, a % b);
}

Python

from math import gcd


def max_points(points):
    n, best = len(points), 1
    for i in range(n):
        slopes = {}
        for j in range(i + 1, n):
            dx = points[j][0] - points[i][0]
            dy = points[j][1] - points[i][1]
            g = gcd(dx, dy)
            dx, dy = dx // g, dy // g
            # One sign per direction: dx > 0, or dx = 0 and dy > 0.
            if dx < 0 or (dx == 0 and dy < 0):
                dx, dy = -dx, -dy
            slopes[(dy, dx)] = slopes.get((dy, dx), 0) + 1
            best = max(best, slopes[(dy, dx)] + 1)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxPoints(vector<vector<int>> &points) {
        int n = points.size(), best = 1;
        for (int i = 0; i < n; i++) {
            map<pair<int, int>, int> slopes;
            for (int j = i + 1; j < n; j++) {
                int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];
                int g = gcd(dx, dy);
                dx /= g, dy /= g;
                // One sign per direction: dx > 0, or dx = 0 and dy > 0.
                if (dx < 0 || (dx == 0 && dy < 0)) dx = -dx, dy = -dy;
                best = max(best, ++slopes[{dy, dx}] + 1);
            }
        }
        return best;
    }
};

More Math & Geometry problems