Waymo
WA
Max Points on a Line
Codinghard
Problem
You are given an array points where points[i] = [xi, yi] represents the coordinates of the i-th point on a 2D plane.
Find the largest number of these points that all lie on some single straight line, and return that count.
Rules to keep in mind:
- A line is determined by any two distinct points, and you need to consider every possible line formed by pairs of the given points.
- All points are guaranteed to be distinct — no two entries in
pointsare identical. - A line can be vertical (undefined slope), so don't assume you can always compute a slope as
dy / dxwithout handling that case separately. - Watch out for floating point precision issues when comparing slopes; consider using integer-based comparisons (e.g., cross products or reduced fraction ratios) instead of dividing.
Examples
Example 1:
Input: points = [[1,1],[3,3],[2,2],[5,1],[8,1]]
Output: 3
Explanation:
- The points
(1,1),(2,2), and(3,3)all satisfyy = x, so they are collinear, giving a line with 3 points. - The points
(1,1),(5,1), and(8,1)all lie ony = 1, which is also a line with 3 points. - No line passes through 4 or more of the given points, so the answer is
3.
Example 2:
Input: points = [[0,0],[0,4],[0,-2],[3,5]]
Output: 3
Explanation:
(0,0),(0,4), and(0,-2)all sharex = 0, forming a vertical line containing 3 points.(3,5)does not lie on that vertical line and does not align with any pair of the other points to form a larger group.- The maximum is therefore
3.
Constraints
1 <= points.length <= 300points[i].length == 2-10^4 <= xi, yi <= 10^4- All given points are distinct.
Solution
Loading editor…
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate