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
Matchsticks to Square INPUT matchsticks array 1 1 2 2 2 i=0 i=1 i=2 i=3 i=4 Visual Matchsticks: L=1 L=1 L=2 L=2 L=2 Total Sum = 1+1+2+2+2 = 8 Side = 8/4 = 2 Conditions: Sum % 4 == 0 [OK] max(arr) <= side [OK] n >= 4 [OK] ALGORITHM STEPS 1 Sort Descending [2,2,2,1,1] - try big first 2 Init 4 Sides sides = [0, 0, 0, 0] 3 Backtrack DFS Try placing each stick 4 Check & Backtrack If side > target, undo Placement Process: S1:2 S2:2 S3:2 S4:2 Place 2 in S1, 2 in S2 Place 2 in S3 Place 1+1 in S4 All sides = 2 [OK] FINAL RESULT Side 1: [2] Side 2 [2] Side 3: [2] Side 4 [1,1] Output: true Square Formed! Each side = 2 units All 5 matchsticks used Key Insight: Use backtracking with pruning: sort descending to fail fast on large sticks, skip duplicates, and prune branches where side sum exceeds target. This reduces time complexity significantly compared to naive approach. Early termination when all sticks placed successfully. TutorialsPoint - Matchsticks to Square | Optimal Backtracking Solution
Asked in
Google 12 Facebook 8 Microsoft 6
128.0K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen