Can every matchstick, used once and unbroken, form a square? Check the total splits by four, sort longest first, then place each stick on a side with room and undo on a dead end, skipping side lengths already tried.
▼The problem
LeetCode 473 (Medium). Given the lengths of some matchsticks, decide whether all of them, each used exactly once and none broken, can form a square.
Examples (LeetCode's): [1,1,2,2,2] → true (total 8, side 2: three twos, and the two ones end to end make the fourth side; scenes 2 and 7); [3,3,3,3,4] → false (scene 8).
The solution
def makesquare(sticks):
side, rem = divmod(sum(sticks), 4)
sticks.sort(reverse=True)
if rem or sticks[0] > side:
return False
sides = [0] * 4
def place(i):
if i == len(sticks):
return True
tried = set()
for s in range(4):
if sides[s] + sticks[i] > side or sides[s] in tried:
continue
tried.add(sides[s])
sides[s] += sticks[i]
if place(i + 1):
return True
sides[s] -= sticks[i]
return False
return place(0)Transcript
Matchsticks to Square. You get matchsticks of different lengths. Use every one exactly once, without breaking any. Can they form a square?
Take one, one, two, two, two. The total is eight, so each side is two. Three twos make three sides, and the two ones, end to end, make the fourth. True.
The naive way tries every stick on every side: four to the n assignments. Over a thousand for five sticks, over a billion for fifteen.
Some piles fail right away: if the total isn't divisible by four, or a stick is longer than a side. Otherwise, sort longest first: the big sticks are hardest to place, so dead ends show up early.
Then backtrack. Place sticks one at a time, on a side with room, never overflowing. If the rest can't be finished, undo and try the next side. One more prune: sides of equal length lead to identical searches, so skip any side whose length was already tried.
In code: find the side, sort, check the early exits, then recurse stick by stick. When all are placed, it's a square. Otherwise, try each side, skipping overflows and repeated lengths: add it, recurse, and take it back if that fails.
Walking the first example, sorted two, two, two, one, one: the twos fill the top, right and bottom, and both ones land on the left. Every side is full. True, without a single undo.
Now three, three, three, three, four. Each side is four; no stick is too long, so no early exit. The four fills the top, and the threes start the other three sides. The last three fits nowhere. Undo. Every other side has a length already tried, so pruning skips them, all the way up. False, after four placements. Without the skip, sixty-four.
Worst case, it's still order four to the n time, and order n space for the recursion. But pruning makes it fast in practice.
Sort, place, prune. That's Matchsticks to Square.