Python coding

Most points on one line

Given a list of points [x, y] with integer coordinates, return the largest number of them that lie on one straight line. A point may appear more than once: every copy counts, and the copies of a point lie on every line through it. An empty list gives 0.

For n points, aim for O(n²).

  • most_on_a_line([[1,1],[2,2],[3,3]]) → 3
  • most_on_a_line([[0,0],[2,1],[4,2],[1,3],[3,0],[6,3]]) → 4
  • most_on_a_line([[1,1],[1,1],[2,3]]) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Fix one point as an anchor. Every line through it is one direction, so group the other points by direction in a hash map; the biggest group is the anchor's best line.

Hint 2

Skip the float dy / dx: vertical lines divide by zero, and large coordinates round two slopes to one value. Divide (dx, dy) by their gcd and flip both signs so the first nonzero one is positive.

Hint 3

Copies of the anchor join every direction: count them apart and add them to the biggest group. Pairing each anchor only with later points still finds every line, from its first point.

Solution and why it works
pythonO(n²) · O(n)
from collections import Counter
from math import gcd

def most_on_a_line(points: list[list[int]]) -> int:
    best = 0
    for i, (x1, y1) in enumerate(points):
        directions = Counter()
        copies = 1                              # the anchor and its duplicates
        for x2, y2 in points[i + 1:]:
            dx, dy = x2 - x1, y2 - y1
            if dx == 0 and dy == 0:
                copies += 1
                continue
            g = gcd(dx, dy)
            dx, dy = dx // g, dy // g
            if dx < 0 or (dx == 0 and dy < 0):  # (1, -2) and (-1, 2) are one line
                dx, dy = -dx, -dy
            directions[(dx, dy)] += 1
        best = max(best, copies + max(directions.values(), default=0))
    return best

Every line through an anchor is one direction, so a map from direction to count finds the anchor's best line in one pass: O(n²) over all anchors, instead of O(n³) for testing each pair against every point. The key must be exact and canonical: (dx, dy) divided by their gcd, with a fixed sign, so (2, 4) and (−1, −2) match. Float slopes fail on vertical lines and on large coordinates. Copies of the anchor lie on every line.

Related lab: Loops in motion