#473
Matchsticks to Square
MediumArrayDynamic ProgrammingBacktrackingBit ManipulationBitmaskBacktrackingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(4^n) | O(4^n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(4^n)Space O(n)
The optimal solution uses backtracking with pruning to efficiently explore valid combinations of matchsticks. By sorting the matchsticks in descending order, we can quickly eliminate impossible configurations.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total length of matchsticks and check if it's divisible by 4.
- 2Step 2: Sort the matchsticks in descending order to try larger sticks first.
- 3Step 3: Use a recursive function to attempt to build each side of the square, backtracking when necessary.
solution.py23 lines
1def makesquare(matchsticks):
2 total_length = sum(matchsticks)
3 if total_length % 4 != 0:
4 return False
5 target = total_length // 4
6 matchsticks.sort(reverse=True)
7
8 sides = [0] * 4
9
10 def backtrack(index):
11 if index == len(matchsticks):
12 return sides[0] == sides[1] == sides[2] == target
13 for i in range(4):
14 if sides[i] + matchsticks[index] <= target:
15 sides[i] += matchsticks[index]
16 if backtrack(index + 1):
17 return True
18 sides[i] -= matchsticks[index]
19 if sides[i] == 0:
20 break
21 return False
22
23 return backtrack(0)ℹ
Complexity note: The complexity remains exponential due to the recursive nature, but sorting the matchsticks helps reduce the number of combinations explored.
- 1The total length must be divisible by 4 to form a square.
- 2Sorting the matchsticks helps in reducing the search space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.