473. Matchsticks to Square
Problem
Decide whether all the matchsticks (given by length) can form a square, using every stick exactly once without breaking any.
Example: [1,1,2,2,2] → true; [3,3,3,3,4] → false
Constraints: up to 15 sticks.
Each side must equal total / 4. Place sticks longest first into one of four sides, backtracking on failure. Two prunings make it fast: skip a side if the stick overflows it, and if a stick doesn't work on an empty side, don't try the other empty sides (they're interchangeable).
Complexity: O(4ⁿ) worst case, tiny in practice with pruning (n ≤ 15).
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
total = sum(matchsticks)
if total % 4:
return False
side = total // 4
sticks = sorted(matchsticks, reverse=True)
if sticks[0] > side:
return False
sides = [0] * 4
def place(i):
if i == len(sticks):
return True # every side <= side and the total is 4·side -> all equal
for k in range(4):
if sides[k] + sticks[i] <= side:
sides[k] += sticks[i]
if place(i + 1):
return True
sides[k] -= sticks[i]
if sides[k] == 0:
break
return False
return place(0)
assert Solution().makesquare([1, 1, 2, 2, 2]) is True
assert Solution().makesquare([3, 3, 3, 3, 4]) is False
assert Solution().makesquare([5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3]) is True
assert Solution().makesquare([10, 6, 5, 5, 5, 3, 3, 3, 2, 2, 2, 2]) is True
assert Solution().makesquare([1, 1, 1]) is False
class Solution {
public boolean makesquare(int[] matchsticks) {
int total = 0;
for (int m : matchsticks) total += m;
if (total % 4 != 0) return false;
Integer[] sticks = Arrays.stream(matchsticks).boxed().sorted(Collections.reverseOrder()).toArray(Integer[]::new);
if (sticks[0] > total / 4) return false;
return place(sticks, 0, new int[4], total / 4);
}
private boolean place(Integer[] sticks, int i, int[] sides, int side) {
if (i == sticks.length) return true;
for (int k = 0; k < 4; k++) {
if (sides[k] + sticks[i] <= side) {
sides[k] += sticks[i];
if (place(sticks, i + 1, sides, side)) return true;
sides[k] -= sticks[i];
}
if (sides[k] == 0) break;
}
return false;
}
}
func makesquare(matchsticks []int) bool {
total := 0
for _, x := range matchsticks {
total += x
}
if total%4 != 0 {
return false
}
side := total / 4
sticks := append([]int{}, matchsticks...)
sort.Sort(sort.Reverse(sort.IntSlice(sticks)))
if sticks[0] > side {
return false
}
var sides [4]int
var place func(i int) bool
place = func(i int) bool {
if i == len(sticks) { // every side <= side and the total is 4*side, so all are equal
return true
}
for k := 0; k < 4; k++ {
if sides[k]+sticks[i] <= side {
sides[k] += sticks[i]
if place(i + 1) {
return true
}
sides[k] -= sticks[i]
}
if sides[k] == 0 {
break
}
}
return false
}
return place(0)
}