Minimum Number of Lines to Cover Points

Bitmask DP — for each subset, try every line through two uncovered points; minimize lines.

Medium
Time O(2^n * n^2) Space O(2^n)
LeetCode
9 min read
geometry bitmask-dp math

Problem#

Return the minimum number of straight lines that pass through all given 2D points (lines may be of any slope, and a line through only one point still counts as a line).

Examples#

  • [[0,1],[2,3],[4,5],[4,3]]2.
  • [[0,2],[-2,-2],[1,4]]1.

Constraints#

  • 1 <= points.length <= 10.

Approach#

With n <= 10, bitmask DP. State: set of uncovered points. For each state, pick the lowest-indexed uncovered point and try pairing it with every other uncovered point to define a line; clear all collinear-on-that-line bits.

Solution#

Minimum Number of Lines to Cover Points
class Solution {
public:
int minimumLines(vector<vector<int>>& points) {
int n = points.size();
if (n <= 2) return 1;
// collinear[i] = bitmask of points collinear with the line through points i and any j (j set elsewhere)
auto cross = [&](int a, int b, int c) {
long long x1 = points[b][0] - points[a][0], y1 = points[b][1] - points[a][1];
long long x2 = points[c][0] - points[a][0], y2 = points[c][1] - points[a][1];
return x1 * y2 - y1 * x2;
};
vector<vector<int>> lineMask(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j) {
int m = (1 << i) | (1 << j);
for (int k = 0; k < n; ++k)
if (k != i && k != j && cross(i, j, k) == 0)
m |= (1 << k);
lineMask[i][j] = lineMask[j][i] = m;
}
int FULL = (1 << n) - 1;
vector<int> dp(1 << n, INT_MAX / 2);
dp[0] = 0;
for (int s = 0; s < (1 << n); ++s) {
if (dp[s] == INT_MAX / 2) continue;
if (s == FULL) continue;
// find lowest uncovered point
int i = __builtin_ctz(~s & FULL);
// option 1: line through just i
int ns = s | (1 << i);
dp[ns] = min(dp[ns], dp[s] + 1);
// option 2: line through i and any other uncovered j
for (int j = 0; j < n; ++j)
if (j != i && !((s >> j) & 1)) {
int t = s | lineMask[i][j];
dp[t] = min(dp[t], dp[s] + 1);
}
}
return dp[FULL];
}
};

Editorial#

With n <= 10 we can afford 2^n states. Fixing the lowest-uncovered point per state breaks symmetry (any line we add must cover it), so we only enumerate O(n) candidate lines per state — total O(2^n n^2). Cross-product collinearity avoids float pitfalls.

Complexity#

  • Time: O(2^n * n^2).
  • Space: O(2^n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.