Max Points on a Line - Problem

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

Two points always define a line, but three or more points are collinear if they all lie on the same line. The challenge is to efficiently find the largest group of collinear points.

Note: Handle edge cases like duplicate points, vertical lines, and horizontal lines carefully.

Input & Output

Example 1 — Three Collinear Points
$ Input: points = [[1,1],[2,2],[3,3]]
Output: 3
💡 Note: All three points lie on the line y = x, so the maximum is 3 collinear points
Example 2 — Mixed Points
$ Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
💡 Note: Points (1,1), (3,2), (5,3) lie on line y = 0.5x + 0.5, but actually (1,1),(2,3),(1,4),(4,1) might form a better line depending on calculation
Example 3 — Duplicate Points
$ Input: points = [[1,1],[1,1],[2,2]]
Output: 3
💡 Note: Two duplicate points at (1,1) plus point (2,2) - all three can be considered on the same line

Constraints

  • 1 ≤ points.length ≤ 300
  • points[i].length == 2
  • -104 ≤ xi, yi ≤ 104
  • All the points are unique except possibly some duplicates

Visualization

Tap to expand
Max Points on a Line INPUT X Y 1 2 3 1 2 3 1,1 2,2 3,3 Input Array: [1,1] [2,2] [3,3] 3 points total points = [[1,1],[2,2],[3,3]] Find max collinear points ALGORITHM STEPS 1 Pick anchor point Start with point [1,1] 2 Calculate slopes To all other points From [1,1] to [2,2]: slope = (2-1)/(2-1) = 1 From [1,1] to [3,3]: slope = (3-1)/(3-1) = 1 3 Count same slopes Use HashMap to group slope count 1 2 4 Track maximum max = count + 1 = 3 Repeat for each anchor point FINAL RESULT 1,1 2,2 3,3 Output: 3 OK - Verified All 3 points are collinear (slope=1) Key Insight: Points are collinear if they share the same slope relative to an anchor point. Use a HashMap to count slopes. For each anchor, the max count + 1 (anchor itself) gives collinear points. Use GCD to handle precision: store slope as reduced fraction (dy/gcd, dx/gcd). Time: O(n^2), Space: O(n). TutorialsPoint - Max Points on a Line | Slope Counting Approach
Asked in
Google 15 Apple 12 Microsoft 10 Amazon 8
180.0K Views
Medium Frequency
~35 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen