简繁EN

LeetCodeNo. 132

[LeetCode with Python] 149. Max Points on a Line

Contents

Problem

Problem page: https://leetcode.com/problems/max-points-on-a-line/
Topics: Hash Table, Math
Difficulty: Hard

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.


Analysis

It's easy to get stuck on a familiar approach to this problem. In high school, we all learned to test whether A, B, and C are collinear by checking whether AB and BC have the same slope. So we pick two points at a time and loop over the other points to see which ones are collinear with those two. Then we take the largest count. The time complexity is O(n3). Picking three points at a time means we repeat a lot of comparisons. Given that cubic running time, there should be a better way.
Instead, we pick just one point at a time and loop over the other points. For each one, we calculate the slope of the line through it and the chosen point, then update the count for that slope in a map (a dictionary). This brings the time complexity down to O(n2) because Python uses a hash table for its dictionaries, so under ideal conditions we can treat insertion and lookup as O(1) operations.
Also, given a point A and two other points B and C collinear with it, the slopes of BA and BC are equal whether B and C are on the same side of A (left or right) or on opposite sides. You can see this in the Cartesian coordinate system.
There are two kinds of points to watch out for:

  1. Points that coincide with the current point. These count toward any line through that point, whatever its slope. For example, if the line through A and B has a 30-degree slope and C coincides with A, then at least three points lie on that line: A, B, and C.
  2. Points on a vertical line through the current point. The slope is infinite in this case. The denominator dx is 0, so we can't divide to calculate the slope and have to keep a separate count.

We also can't use the floating-point slope float(dy) / dx directly as a dictionary key. When the coordinates are large, different slopes can round to the same floating-point number. For example, the three points (0,0), (94911151,94911150), and (94911152,94911151) aren't collinear, but the slopes from (0,0) to the other two points both round to 0.9999999894638303, so counting by floating-point slope gives 3. The coordinates in this problem are all integers, so I first divide dy and dx by their greatest common divisor. If dx is negative, I negate both dy and dx. Then I use the integer pair (dy, dx) as the dictionary key, so slopes and keys correspond one to one. I use the Euclidean algorithm to find the greatest common divisor. Its loop count grows logarithmically with the coordinate differences, so the total time is O(n2 log C), where C is the largest absolute coordinate difference. If the coordinate range is small, though, it's fine to treat it as O(n2).


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution:
# @param a, b, non-negative integers, not both zero
# @return their greatest common divisor
def gcd(self, a, b):
while 0 != b:
a, b = b, a % b
return a

# @param points, a list of Points
# @return an integer
def maxPoints(self, points):
len_points = len(points)
if len_points <= 1:
return len_points
max_count = 0
for index1 in range(0, len_points):
p1 = points[index1]
gradients = {}
infinite_count = 0
duplicate_count = 0
for index2 in range(index1, len_points):
p2 = points[index2]
dx = p2.x - p1.x
dy = p2.y - p1.y
if 0 == dx and 0 == dy:
duplicate_count += 1
if 0 == dx:
infinite_count += 1
else:
# take care: a float slope may round two different slopes to
# the same value, so use the reduced pair (dy, dx) with dx > 0
d = self.gcd(abs(dy), abs(dx))
dy, dx = dy // d, dx // d
if dx < 0:
dx, dy = -dx, -dy
g = (dy, dx)
gradients[g] = (gradients[g] + 1 if gradients.has_key(g) else 1)
if infinite_count > max_count:
max_count = infinite_count
for k, v in gradients.items():
v += duplicate_count
if v > max_count:
max_count = v
return max_count

Article link: https://xnerv.wang/en/leetcode-max-points-on-a-line/