Matchsticks to Square (LeetCode 473): Solution and Explanation

Medium
Array
Dynamic programming
Backtracking
Bit manipulation
Bitmask

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

  1. Compute total. If total % 4 != 0, return false. Otherwise side = total / 4.
  2. Sort the sticks in descending order. If the longest is greater than side, return false.
  3. Keep sides = [0, 0, 0, 0] and call dfs(0). If i == n, every stick is placed, so return true.
  4. For stick i, try each side j: skip it if sides[j] + stick > side, and skip it if sides[j] == sides[j - 1] because that branch was already explored.
  5. Otherwise add the stick to side j, recurse on i + 1, and return true if that succeeds. If not, remove the stick and try the next side.
  6. If no side works, return false so the caller can move its own stick.

Step-by-step example

matchsticks = [1,1,2,2,2]
  1. The total is 8, which divides by 4, so each side must be 2.
  2. Sorted longest first the sticks are [2,2,2,1,1]. The longest, 2, fits on a side.
  3. Stick 2 goes on the top side (2/2). The next 2 overflows the top, so it goes on the right side (2/2).
  4. The third 2 overflows top and right, so it goes on the bottom (2/2).
  5. Stick 1 overflows the first three sides and goes on the left (1/2). The last 1 also lands on the left (2/2).
  6. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 % 4 check. 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] += stick after 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.