15% off all plans & roadmaps Use code
See plansProblem editorial
You are given matchsticks, where each integer represents the length of one matchstick. Matchsticks may be arranged end to end, but they cannot be broken, and every matchstick must be used exactly once.
Matchsticks to Square is a Backtracking Patterns problem, in the N-Queens / Constraint Satisfaction subpattern. The pattern covers subsets, permutations, combinations, N-Queens, and word search
The reference solution runs in O(4^n) worst case, where n is matchsticks.size(), plus O(n log n) for sorting. time and O(n) for the recursion stack; the four side totals use O(1) additional space. space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Matchsticks to Square is a Backtracking Patterns problem, in the N-Queens / Constraint Satisfaction subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.