Matchsticks to Square (LeetCode 473): Solution and Explanation
Each matchstick has a length. Using every stick exactly once and never breaking one, decide whether they can be arranged into the four equal sides of a square.
Intuition
Every stick ends up on the outline, so the perimeter is fixed: it is the sum of all lengths. Each side must therefore be exactly sum / 4. If the sum is not divisible by 4, or one stick is longer than a side, the answer is false before any search.
After that, the problem is a placement puzzle: give every stick to one of four buckets so that every bucket fills to exactly the side length. Since the total is exactly four sides, it is enough to never let a bucket go over the target. When the last stick is placed, all four are full.
Plain backtracking tries up to 4^n assignments, so pruning matters. Placing the longest sticks first makes overflow happen early, near the top of the search tree, where cutting a branch removes the most work.
The second prune removes symmetry. If two sides currently hold the same length, putting the stick on either produces the same picture rotated, so only the first of them needs to be tried. In particular, an empty stick is only ever placed on the first empty side.
Approach: Backtracking with sorting and symmetry pruning
- Compute
total. Iftotal % 4 != 0, return false. Otherwiseside = total / 4. - Sort the sticks in descending order. If the longest is greater than
side, return false. - Keep
sides = [0, 0, 0, 0]and calldfs(0). Ifi == n, every stick is placed, so return true. - For stick
i, try each sidej: skip it ifsides[j] + stick > side, and skip it ifsides[j] == sides[j - 1]because that branch was already explored. - Otherwise add the stick to side
j, recurse oni + 1, and return true if that succeeds. If not, remove the stick and try the next side. - If no side works, return false so the caller can move its own stick.
Step-by-step example
matchsticks = [1,1,2,2,2]
- The total is 8, which divides by 4, so each side must be 2.
- Sorted longest first the sticks are [2,2,2,1,1]. The longest, 2, fits on a side.
- Stick 2 goes on the top side (2/2). The next 2 overflows the top, so it goes on the right side (2/2).
- The third 2 overflows top and right, so it goes on the bottom (2/2).
- Stick 1 overflows the first three sides and goes on the left (1/2). The last 1 also lands on the left (2/2).
- All five sticks are placed with every side at 2, so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def makesquare(self, matchsticks: List[int]) -> bool:
3 total = sum(matchsticks)
4 if total % 4 != 0:
5 return False
6 side = total // 4
7 matchsticks.sort(reverse=True)
8 if matchsticks[0] > side:
9 return False
10 sides = [0] * 4
11
12 def dfs(i):
13 if i == len(matchsticks):
14 return True
15 for j in range(4):
16 if sides[j] + matchsticks[i] > side:
17 continue
18 if j > 0 and sides[j] == sides[j - 1]:
19 continue
20 sides[j] += matchsticks[i]
21 if dfs(i + 1):
22 return True
23 sides[j] -= matchsticks[i]
24 return False
25
26 return dfs(0)1class Solution {
2 private int[] sides;
3 private int side;
4
5 public boolean makesquare(int[] matchsticks) {
6 int total = 0;
7 for (int m : matchsticks) total += m;
8 if (total % 4 != 0) return false;
9 side = total / 4;
10 Arrays.sort(matchsticks);
11 for (int l = 0, r = matchsticks.length - 1; l < r; l++, r--) {
12 int t = matchsticks[l]; matchsticks[l] = matchsticks[r]; matchsticks[r] = t;
13 }
14 if (matchsticks[0] > side) return false;
15 sides = new int[4];
16 return dfs(matchsticks, 0);
17 }
18
19 private boolean dfs(int[] sticks, int i) {
20 if (i == sticks.length) return true;
21 for (int j = 0; j < 4; j++) {
22 if (sides[j] + sticks[i] > side) continue;
23 if (j > 0 && sides[j] == sides[j - 1]) continue;
24 sides[j] += sticks[i];
25 if (dfs(sticks, i + 1)) return true;
26 sides[j] -= sticks[i];
27 }
28 return false;
29 }
30}1class Solution {
2public:
3 bool makesquare(vector<int>& matchsticks) {
4 int total = 0;
5 for (int m : matchsticks) total += m;
6 if (total % 4 != 0) return false;
7 side = total / 4;
8 sort(matchsticks.begin(), matchsticks.end(), greater<int>());
9 if (matchsticks[0] > side) return false;
10 sides.assign(4, 0);
11 return dfs(matchsticks, 0);
12 }
13
14private:
15 vector<int> sides;
16 int side = 0;
17
18 bool dfs(vector<int>& sticks, int i) {
19 if (i == (int)sticks.size()) return true;
20 for (int j = 0; j < 4; j++) {
21 if (sides[j] + sticks[i] > side) continue;
22 if (j > 0 && sides[j] == sides[j - 1]) continue;
23 sides[j] += sticks[i];
24 if (dfs(sticks, i + 1)) return true;
25 sides[j] -= sticks[i];
26 }
27 return false;
28 }
29};Time and space complexity
O(4^n)
In the worst case each of the n sticks is tried on four sides. Sorting and skipping equal sides prune most branches, which is why n up to 15 runs quickly.
O(n)
The recursion is at most n levels deep and the side array has four entries.
Other approaches
Bitmask DP (time O(n * 2^n), space O(2^n))
Let dp[mask] be the length of the side currently being filled after using the sticks in mask, or -1 if unreachable. Add one unused stick at a time if it does not overflow the current side, wrapping to 0 when a side completes. The answer is whether the full mask is reachable.
Fill one side at a time (time O(4^n), space O(n))
Build the first side completely from unused sticks, then the second, and so on, backtracking over subsets. It is the same idea as Partition to K Equal Sum Subsets with k = 4.
Common mistakes
- Skipping the
total % 4check. Integer division then gives a side length that silently drops the remainder. - Sorting ascending. Small sticks first creates a huge number of partial layouts before any overflow is detected.
- Forgetting to undo
sides[j] += stickafter a failed recursion, which leaves the stick counted on two sides. - Using the duplicate-side prune with the wrong neighbour. Comparing with the previous side only works because equal sides are interchangeable at that moment.
Frequently asked questions
Why is it enough to check that no side overflows?
The four sides together must hold exactly total = 4 * side. If none of them exceeds side once every stick is placed, all of them must equal side.
Why does skipping a side equal to the previous one not lose answers?
The two sides hold the same length, so placing the stick on the second gives a state that is just the first case with the sides relabeled. Any square found from it would already have been found from the first.
Is this the same as Partition to K Equal Sum Subsets?
Yes, with k fixed to 4. The same pruning ideas apply, and the bitmask DP version also carries over directly.
Can the sum overflow a 32-bit integer?
At most 15 sticks of length up to 10^8 sum to 1.5 * 10^9, which still fits in a signed 32-bit integer.