Matchsticks to Square - Problem
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.
Input & Output
Example 1 — Perfect Square
$
Input:
matchsticks = [1,1,2,2,2]
›
Output:
true
💡 Note:
Total length is 8, so each side needs length 2. We can group as: Side 1: [2], Side 2: [2], Side 3: [2], Side 4: [1,1]. All sides have length 2.
Example 2 — Impossible Square
$
Input:
matchsticks = [3,3,3,3,4]
›
Output:
false
💡 Note:
Total length is 16, so each side needs length 4. But we have three matchsticks of length 3, and 3 < 4, so we can't form sides of length 4 with these.
Example 3 — Single Large Stick
$
Input:
matchsticks = [5,5,5,5,4,4,4,4,4,4]
›
Output:
false
💡 Note:
Total is 44, not divisible by 4. Cannot form a square when total length is not divisible by 4.
Constraints
- 1 ≤ matchsticks.length ≤ 15
- 1 ≤ matchsticks[i] ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of matchstick lengths
2
Process
Group into 4 sides with equal sums
3
Output
True if square possible, false otherwise
Key Takeaway
🎯 Key Insight: This is a partition problem - we need to divide matchsticks into 4 groups with equal sums
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code