progress

~/problems / Arrays & hashing / Hash maps and counting

Maximum Points on a Line

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

hard ~30 min

Given a list of distinct points [x, y] with integer coordinates, write max_points(points: list[list[int]]) -> int returning the largest number of them that lie on a single straight line.

⭐ Bonus: checking every pair of points against every third point (O(n³)) still passes; a speed test on the largest inputs earns a star at about O(n² log C), where C bounds the coordinates.

max_points([[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]])  # 4  ([3,2], [4,1], [2,3], [1,4])
Six points; four of them, (4, 1), (3, 2), (2, 3) and (1, 4), lie on the line x + y = 5, the most on any line
max_points([[1, 1], [2, 2], [3, 3]])                          # 3
max_points([[0, 0]])                                          # 1

Constraints: 1 ≤ len(points) ≤ 500 in Python (up to 2,500 in C++ and Java, so the speed test still needs O(n²)-ish work there), -10^9 ≤ x, y ≤ 10^9, all points distinct.

Show hint

Fix one anchor point and group every other point by the direction from the anchor to it: points sharing a direction are collinear with the anchor. The trap is representing a direction exactly. Float slopes break on vertical lines and round nearly equal slopes together; reduce (dx, dy) by their gcd and normalise the sign instead.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc