Skip to content

473. Matchsticks To Square

Array Dynamic Programming Backtracking Bit Manipulation Bitmask

Problem - Matchsticks To Square

Medium

You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

Return true if you can make this square and false otherwise.

 

Example 1:

Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

Example 2:

Input: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.

 

Constraints:

  • 1 <= matchsticks.length <= 15
  • 1 <= matchsticks[i] <= 108

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def makesquare(self, matchsticks: List[int]) -> bool:
        @cache
        def dfs(state, val):
            if state == (1 << len(matchsticks)) - 1:
                return True
            for i, num in enumerate(matchsticks):
                if state & (1 << i):
                    continue
                if val + num > div:
                    break
                if dfs(state | (1 << i), (val + num) % div):
                    return True
            return False

        div, mod = divmod(sum(matchsticks), 4)
        matchsticks.sort()

        if mod:
            return False

        return dfs(0, 0)

Submission Stats:

  • Runtime: 295 ms (55.94%)
  • Memory: 31.5 MB (6.89%)