Problem Description
Given an array of points where each point is represented as [x, y], find the maximum number of points that lie on a single straight line.
Key Insights
- Use a nested loop to treat each point as an anchor and calculate slopes to all other points.
- Represent slopes as a reduced fraction (dy/dx) using the greatest common divisor (gcd) to avoid floating-point imprecision.
- Specially handle vertical lines (when dx is 0) by using a unique identifier.
- The problem naturally leads to an O(n²) solution by processing each pair of points.
- Use a hash table (or dictionary) to count how many points form the same slope with the anchor point.
Space and Time Complexity
Time Complexity: O(n²) where n is the number of points, since every pair of points is compared. Space Complexity: O(n) for the hash table used for storing slope counts for each anchor point.
Solution
The solution iterates through each point and treats it as an anchor. For every other point, we calculate the slope between the anchor and that point. The slope is computed as a pair (dy, dx) reduced to its simplest form via gcd. For vertical lines (dx == 0), we use a special key. A hash table is used to count occurrences of each slope. The maximum number of points with the same slope (plus the anchor) is recorded. The final result is the maximum count from all anchors.