Skip to main content
Back to problems
#2152
Medium Algorithms

Minimum number of lines to cover points

Array Hash Table Math Dynamic Programming Backtracking Bit Manipulation Geometry Bitmask
43.9% acceptance
Mar 31, 2026
77
14

No description available.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_lines(points: Vec<Vec<i32>>) -> i32 {
    let n = points.len();
    if n <= 2 {
      return 1;
    }

    let mut lines: Vec<u32> = Vec::new();
    for i in 0..n {
      for j in (i+1)..n {
        let mut mask = (1u32 << i) | (1u32 << j);
        for k in 0..n {
          if k == i || k == j {
            continue;
          }
          // Check collinearity using cross product
          let dx1 = points[j][0] - points[i][0];
          let dy1 = points[j][1] - points[i][1];
          let dx2 = points[k][0] - points[i][0];
          let dy2 = points[k][1] - points[i][1];
          if dx1 as i64 * dy2 as i64 == dy1 as i64 * dx2 as i64 {
            mask |= 1u32 << k;
          }
        }
        lines.push(mask);
      }
    }
    
    // Also add single-point lines
    for i in 0..n {
      lines.push(1u32 << i);
    }
    
    lines.sort_unstable();
    lines.dedup();

    let full = (1u32 << n) - 1;
    let mut dp = vec![i32::MAX; (full + 1) as usize];
    dp[0] = 0;

    for covered in 0..=full {
      if dp[covered as usize] == i32::MAX {
        continue;
      }
      for &line in &lines {
        let new_covered = covered | line;
        dp[new_covered as usize] = dp[new_covered as usize].min(dp[covered as usize] + 1);
      }
    }

    dp[full as usize]
  }
}