SDE & MLE Prep

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)