Skip to content
Problem 473 · LeetCode 473(opens in a new tab)

Matchsticks to Square

MediumBacktracking

You get a list of stick lengths, matchsticks. Use every stick exactly once to build the outline of a square. Sticks can be laid end to end along a side, but none can be cut.

Return true if such a square exists, and false otherwise.

Example 1

Input:  matchsticks = [3, 2, 7, 2, 2, 3, 2, 7]
Output: true
Why:    sides 7, 7, 3 + 2 + 2 and 3 + 2 + 2
2 more examples and the constraints

Example 2

Input:  matchsticks = [2, 2, 2, 3, 3]
Output: false
Why:    each side must be 3, and no 2 can be part of one

Example 3

Input:  matchsticks = [1, 1, 1, 1, 1]
Output: false
Why:    a total of 5 cannot split into four equal sides

Constraints

  • 1 ≤ number of sticks ≤ 15
  • 1 ≤ each length ≤ 100,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every side for every stickO(4ⁿ)
  2. One side at a time, with a memoO(n · 2ⁿ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 15 sticks, worst caseVerdict
Try every side for every stickO(4ⁿ)
Fine on easy inputs; blows up on hard ones
One side at a time, with a memoO(n · 2ⁿ)
Best; every dead end is paid for once

n = number of sticks, at most 15. 4¹⁵ is about 1 billion; 15 · 2¹⁵ is about 500,000.

Edge cases to test

  • Fewer than four sticks. [7] or [4, 4] can never make four sides.
  • Total not divisible by 4. Return false before any search.
  • One stick too long. [1, 1, 1, 9] has side 3, and the 9 fits nowhere.
  • Right total, wrong shapes. [2, 2, 2, 3, 3] adds up to 12, but no side of 3 can use a 2.
  • Very long sticks. Four sticks of 100,000,000 total 400,000,000, which still fits in a 32-bit int.

Common mistakes

  • Checking only that the total divides by 4, without searching.
  • Memoising on the side lengths instead of the used sticks, which misses that the mask fixes the state.
  • Forgetting to undo a placement after a failed branch.

How to talk through it

  1. 1Clarify. Must every stick be used? Can sticks be broken? How many sticks at most?
  2. 2Cheap checks first. The total must divide by 4, and no stick may be longer than a side.
  3. 3Give the backtracking. Try each stick on each side: correct, but up to 4ⁿ branches.
  4. 4Find the real state. The set of used sticks decides everything, so a bitmask memo caps the work at n · 2ⁿ.
  5. 5Test out loud. Run a total not divisible by 4, a stick too long, and a right total that still fails.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?