Minimum Number of Lines to Cover Points - Problem

You are given an array points where points[i] = [xi, yi] represents a point on an X-Y plane.

Straight lines are going to be added to the X-Y plane, such that every point is covered by at least one line.

Return the minimum number of straight lines needed to cover all the points.

Input & Output

Example 1 — Basic Case
$ Input: points = [[1,1],[2,2],[3,4],[4,5],[5,5]]
Output: 3
💡 Note: One possible solution: Line 1 passes through (1,1) and (2,2); Line 2 passes through (3,4) and (4,5); Line 3 passes through (5,5). Total: 3 lines.
Example 2 — Collinear Points
$ Input: points = [[1,1],[2,2],[3,3],[4,4]]
Output: 1
💡 Note: All points are collinear (on the line y=x), so only 1 line is needed to cover all points.
Example 3 — Minimum Case
$ Input: points = [[1,1],[2,3]]
Output: 1
💡 Note: Any two points can be covered by exactly one line.

Constraints

  • 1 ≤ points.length ≤ 20
  • points[i].length == 2
  • -100 ≤ points[i][0], points[i][1] ≤ 100

Visualization

Tap to expand
Minimum Number of Lines to Cover Points INPUT 1 2 3 4 5 (1,1) (2,2) (3,4) (4,5) (5,5) Input Array: points = [[1,1],[2,2], [3,4],[4,5],[5,5]] 5 points on X-Y plane n = 5 (bitmask: 5 bits) ALGORITHM STEPS 1 Precompute Lines For each pair of points, find all points on that line 2 Create Bitmasks Each line = bitmask of covered points Line(1,1)-(2,2): 00011 Line(4,5)-(5,5): 11000 Line(3,4)-(4,5): 01100 3 DP with Bitmask dp[mask] = min lines to cover points in mask dp[mask|line] = min(dp[mask|line], dp[mask]+1) 4 Find Minimum Return dp[(1<<n)-1] = dp[11111] = 3 FINAL RESULT Line 1: (1,1)-(2,2) Line 2: (4,5)-(5,5) Line 3: (3,4)-(4,5) Output: 3 Minimum Lines All 5 points covered! [OK] Solution verified Key Insight: Use bitmask DP where each state represents which points are covered. For n points, we have 2^n states. Precompute all possible lines between point pairs, then greedily try adding each line to minimize total count. Time Complexity: O(2^n * n^2) | Space Complexity: O(2^n + n^2) for DP table and line masks. TutorialsPoint - Minimum Number of Lines to Cover Points | Dynamic Programming with Bitmask
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
485 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