Matchsticks to Square
Hard
Topics
You are given an array nums where nums[i] is the length of the i-th matchstick. You must use every matchstick exactly once, joining them (without breaking any) to form a square. Return true if you can form a square, otherwise false.
Example 1
Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: Sides of length 2: {2},{2},{2},{1,1}.
Example 2
Input: matchsticks = [3,3,3,3,4] Output: false
Constraints
- 1 <= nums.length <= 15
- 1 <= nums[i] <= 10^8
Editorial — intuition, approach, complexity and pitfalls
Intuition
Every matchstick must be used and none may be broken, so the four sides each have length total / 4. If the total is not divisible by four, or any single stick exceeds that side length, it is impossible before any search begins.
What remains is a partition search: assign each stick to one of four buckets without exceeding the side length. Two prunings do the real work. Sort descending so the awkward long sticks are placed first and dead ends are discovered shallow rather than deep. And skip a bucket whose running total equals the previous bucket's — those two buckets are interchangeable, so trying both explores identical subtrees.
Approach
- Reject immediately if there are fewer than four sticks or the total is not divisible by four.
- Sort descending and reject if the longest stick exceeds the side length.
- Place sticks one at a time, trying each of the four buckets.
- Skip a bucket whose total equals the bucket before it.
- Succeed when every stick has been placed.
Dry Run
nums = [1,1,2,2,2] total 8, side 2
sorted descending [2,2,2,1,1]
place 2 -> buckets [2,0,0,0]
place 2 -> bucket 1 is full, bucket 2 has total 0 = bucket 3's total, so only
one empty bucket is tried -> [2,2,0,0]
place 2 -> [2,2,2,0]
place 1 -> [2,2,2,1]
place 1 -> [2,2,2,2] all four sides complete
answer true
[3,3,3,3,4] -> false total 16, side 4, but no combination of 3s makes 4Complexity
- Time — O(4ⁿ) in the worst case, with the two prunings cutting it dramatically in practice. At the stated bound of 15 sticks the unpruned tree is about 10⁹ nodes; the descending sort and the equal-bucket skip make it tractable.
- Space — O(n) for the recursion depth, plus four counters. The bitmask dynamic program over subsets is the alternative: O(2ⁿ · n) time and O(2ⁿ) space, which at n = 15 is 32,768 states and strictly better than exponential search — worth offering as the follow-up.
Common Pitfalls
- Omitting the equal-bucket skip. Without it the search explores four symmetric copies of every assignment and the running time multiplies accordingly.
- Sorting ascending, or not sorting. Placing the short sticks first defers the hard decisions and the search explodes.
- Filling one side completely before starting the next. That is a legitimate alternative formulation but needs its own backtracking over which sticks form each side; mixing the two is where bugs appear.
- Forgetting the
fewer than four stickscheck. Four sides need at least four sticks, and without the check a short array can pass the divisibility test and then silently succeed. - Checking only the total and not the longest stick. A stick longer than one side can never be placed, and catching it up front saves the whole search.
- Assuming each side uses the same number of sticks. It need not; only the sums must match.
Full Solution — all languages
class Solution:
def makesquare(self, nums):
m = nums
n = len(m)
total = sum(m)
if n < 4 or total % 4 != 0:
return False
side = total // 4
arr = sorted(m, reverse=True)
if arr[0] > side:
return False
sides = [0, 0, 0, 0]
def dfs(idx):
if idx == n:
return True
for s in range(4):
if s > 0 and sides[s] == sides[s - 1]:
continue
if sides[s] + arr[idx] <= side:
sides[s] += arr[idx]
if dfs(idx + 1):
return True
sides[s] -= arr[idx]
return False
return dfs(0)import java.util.*;
class Solution {
public boolean makesquare(int[] nums) {
int n = nums.length;
long total = 0;
for (int v : nums) total += v;
if (n < 4 || total % 4 != 0) return false;
sideLen = total / 4;
arr = nums.clone();
Arrays.sort(arr);
for (int i = 0; i < n / 2; i++) {
int t = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = t;
}
if (arr[0] > sideLen) return false;
sides = new long[4];
return dfs(0);
}
long[] sides;
long sideLen;
int[] arr;
private boolean dfs(int idx) {
if (idx == arr.length) return true;
for (int s = 0; s < 4; s++) {
if (s > 0 && sides[s] == sides[s - 1]) continue;
if (sides[s] + arr[idx] <= sideLen) {
sides[s] += arr[idx];
if (dfs(idx + 1)) return true;
sides[s] -= arr[idx];
}
}
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool makesquare(vector<int>& nums) {
vector<int> arr = nums;
int n = arr.size();
long long total = 0;
for (int v : arr) total += v;
if (n < 4 || total % 4 != 0) return false;
long long side = total / 4;
sort(arr.rbegin(), arr.rend());
if (arr[0] > side) return false;
vector<long long> sides(4, 0);
function<bool(int)> dfs = [&](int idx) -> bool {
if (idx == n) return true;
for (int s = 0; s < 4; s++) {
if (s > 0 && sides[s] == sides[s - 1]) continue;
if (sides[s] + arr[idx] <= side) {
sides[s] += arr[idx];
if (dfs(idx + 1)) return true;
sides[s] -= arr[idx];
}
}
return false;
};
return dfs(0);
}
};/**
* @param {number[]} nums
* @return {boolean}
*/ var makesquare = function(nums) {
const m = nums, n = m.length;
let total = 0;
for (let i = 0; i < n; i++) total += m[i];
if (n < 4 || total % 4 !== 0) return false;
const side = total / 4;
const arr = m.slice().sort((x, y) => y - x);
if (arr[0] > side) return false;
const sides = [0, 0, 0, 0];
const dfs = (idx) => {
if (idx === n) return true;
for (let s = 0; s < 4; s++) {
if (s > 0 && sides[s] === sides[s - 1]) continue;
if (sides[s] + arr[idx] <= side) {
sides[s] += arr[idx];
if (dfs(idx + 1)) return true;
sides[s] -= arr[idx];
}
}
return false;
};
return dfs(0);
};