Matchsticks to Square

Hard

Topics
ArrayBacktrackingBitmaskDynamic Programming

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

1011222324
Input:  matchsticks = [1,1,2,2,2]
Output: true
Explanation: Sides of length 2: {2},{2},{2},{1,1}.

Example 2

3031323344
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

  1. Reject immediately if there are fewer than four sticks or the total is not divisible by four.
  2. Sort descending and reject if the longest stick exceeds the side length.
  3. Place sticks one at a time, trying each of the four buckets.
  4. Skip a bucket whose total equals the bucket before it.
  5. 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 4

Complexity

  • 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 sticks check. 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)
Asked at eBay PhonePe
SensAI
Beta
Tap the mic to stop voice mode