Matchsticks to Square - Problem
Imagine you have a collection of matchsticks of different lengths, and you want to arrange them to form a perfect square! ๐ฅ
Given an integer array matchsticks where matchsticks[i] represents the length of the i-th matchstick, your task is to determine whether you can use all the matchsticks to construct exactly one square.
Rules:
- You must use every single matchstick exactly once
- You cannot break or cut any matchstick
- You can connect matchsticks end-to-end to form longer sides
- All four sides of the square must have equal length
Goal: Return true if it's possible to form a square, false otherwise.
Example: If you have matchsticks [1,1,2,2,2], you can form a square with sides of length 2 each: [1+1], [2], [2], [2] โ
Input & Output
example_1.py โ Basic Square Formation
$
Input:
[1,1,2,2,2]
โบ
Output:
true
๐ก Note:
You can form a square with perimeter 8: each side has length 2. Arrange as [1+1], [2], [2], [2] for the four sides.
example_2.py โ Impossible Configuration
$
Input:
[3,3,3,3,4]
โบ
Output:
false
๐ก Note:
Total length is 16, so each side should be 4. But we have four sticks of length 3 and one of length 4, making it impossible to form equal sides.
example_3.py โ Perfect Match
$
Input:
[5,5,5,5,4,4,4,4,3,3,3,3]
โบ
Output:
true
๐ก Note:
Total is 48, each side should be 12. We can arrange as [5+4+3], [5+4+3], [5+4+3], [5+4+3] to form a perfect square.
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Target
Add up all matchstick lengths and divide by 4 - this is your target side length
2
Sort Strategy
Sort matchsticks from longest to shortest - try big pieces first for faster failure detection
3
Backtrack & Assign
Try placing each matchstick on any side that has room, backtrack when stuck
4
Optimize & Prune
Skip equivalent empty sides and impossible configurations to speed up search
Key Takeaway
๐ฏ Key Insight: Sort matchsticks in descending order and use backtracking with aggressive pruning - this transforms an exponential problem into something manageable by failing fast on impossible configurations!
Time & Space Complexity
Time Complexity
O(4^n)
For each of n matchsticks, we try placing it on any of 4 sides
โ Linear Growth
Space Complexity
O(n)
Recursion stack depth equals number of matchsticks
โก Linearithmic Space
Constraints
- 1 โค matchsticks.length โค 15
- 1 โค matchsticks[i] โค 108
- Key insight: Total sum must be divisible by 4
- All matchsticks must be used exactly once
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code