#473
Medium Algorithms Matchsticks to square
Array Dynamic Programming Backtracking Bit Manipulation Bitmask
41.6% acceptance
Jan 13, 2026
4021
309
You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true if you can make this square and false otherwise.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn makesquare(mut matchsticks: Vec<i32>) -> bool {
let sum: i32 = matchsticks.iter().sum();
if sum % 4 != 0 { return false; }
let target = sum / 4;
matchsticks.sort_by(|a, b| b.cmp(a));
let mut sides = vec![0; 4];
Self::dfs(&matchsticks, 0, &mut sides, target)
}
fn dfs(sticks: &[i32], idx: usize, sides: &mut Vec<i32>, target: i32) -> bool {
if idx == sticks.len() {
return sides.iter().all(|&s| s == target);
}
for i in 0..4 {
if sides[i] + sticks[idx] <= target {
sides[i] += sticks[idx];
if Self::dfs(sticks, idx + 1, sides, target) { return true; }
sides[i] -= sticks[idx];
}
if sides[i] == 0 { break; }
}
false
}
}