Skip to main content

Matchsticks to Square - Solution & Explanation

MediumArrayDynamic ProgrammingBacktrackingBit Manipulation10 min readAsked at: Amazon, Meta, Uber +6
Practice this problem

Problem Statement

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.

 

Example 1:

Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

Example 2:

Input: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.

 

Constraints:

  • 1 <= matchsticks.length <= 15
  • 1 <= matchsticks[i] <= 108

Approach Overview

Problem Overview: You are given an array where each value represents the length of a matchstick. The task is to determine whether all matchsticks can be used exactly once to form a square. That means dividing the sticks into four groups with equal total length.

Approach 1: Backtracking (O(4^n) time, O(n) space)

The idea is to simulate building the four sides of the square. First compute the total length of all matchsticks; if it is not divisible by four, forming a square is impossible. After sorting the array in descending order, recursively try placing each matchstick into one of four sides. At every step you add the current stick to a side if the side length does not exceed the target length (total / 4). If all sticks are placed and every side equals the target, a valid square exists. Sorting helps prune the search earlier because longer sticks fail faster. This is a classic backtracking exploration over an array with aggressive pruning to reduce unnecessary branches.

Approach 2: Dynamic Programming with Bitmasking (O(n · 2^n) time, O(2^n) space)

This approach treats each subset of matchsticks as a state. A bitmask represents which sticks have already been used. For every mask, store the current side length modulo the target side length. Iterate through all masks and try adding a new unused matchstick if it does not exceed the side limit. When the side length reaches the target, it resets to zero and the next side begins. If the full mask ((1 << n) - 1) is reachable with remainder zero, all sticks can be partitioned into four equal sides. This method leverages dynamic programming combined with bitmask state compression to systematically explore subsets instead of recursive branching.

Recommended for interviews: Backtracking is the most common solution expected by interviewers. It shows your ability to design recursive search with pruning and constraints. The bitmask DP solution is more advanced and demonstrates strong knowledge of subset DP patterns, which can stand out in senior-level interviews.

Approach 1: Backtracking

This approach involves using backtracking to attempt fitting matchsticks into four equal-length sides. First, calculate the potential side length as the total sum of matchsticks divided by four. Each matchstick will be assigned to one of the four sides iteratively. If a proper combination is found, a square can be formed.

The matchsticks array is sorted in descending order to optimize the process, ensuring that larger matchsticks are placed first. This reduces the number of recursive calls by filling up spaces more quickly.

The Python solution uses a recursive function backtrack that attempts to assign each matchstick to one of the four sides. The search attempts adding the current matchstick to any side, and checks recursively if that yields a valid solution. The matchsticks array is sorted in descending order to try larger matchsticks first.

Code

Python

Java

Complexity

Time Complexity: O(4^N), where N is the length of matchsticks and 4 is because each matchstick could theoretically fit into one of four sides.
Space Complexity: O(N) due to the recursion stack.

Try this approach in the editor →

Approach 2: Dynamic Programming with Bitmasking

This approach leverages dynamic programming combined with bitmasking to efficiently explore combinations of matchsticks placed into sides. The DP state represents which matchsticks have been used, and the transition involves trying to extend the current side or start a new side once the correct length is reached.

This C++ implementation uses DP with bit masking. The memo map stores results of subproblems, reducing repeated calculations. The core logic places matchsticks into slots, trying all combinations using recursion augmented by memoization.

Code

C++

JavaScript

Complexity

Time Complexity: O(2^N * N), where N is the number of matchsticks, due to exploring all states.
Space Complexity: O(2^N) for memoization.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Backtracking

Time Complexity: O(4^N), where N is the length of matchsticks and 4 is because each matchstick could theoretically fit into one of four sides.
Space Complexity: O(N) due to the recursion stack.

Dynamic Programming with Bitmasking

Time Complexity: O(2^N * N), where N is the number of matchsticks, due to exploring all states.
Space Complexity: O(2^N) for memoization.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Backtracking with PruningO(4^n)O(n)Most common interview solution; easy to reason about with pruning and sorting
Dynamic Programming with BitmaskO(n · 2^n)O(2^n)When practicing subset DP or optimizing repeated state exploration

Video Solution

Matchsticks to Square - Leetcode 473 - PythonNeetCode40,177 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Matchsticks to Square easy or hard?
Matchsticks to Square is considered a Medium difficulty problem. The core challenge is designing efficient pruning in the backtracking search and recognizing that the total length must be divisible by four before attempting any recursion.
Matchsticks to Square Python/Java solution
Python and Java solutions typically implement a recursive backtracking strategy. The algorithm sorts matchsticks in descending order and tries to assign each stick to one of four sides while maintaining the target side length constraint.
How to solve Matchsticks to Square in O(n)?
An O(n) solution is not possible because the problem requires exploring combinations of matchsticks. The closest optimized approach is dynamic programming with bitmasking, which runs in O(n · 2^n). This method stores subset states and tracks the current side length modulo the target side length.
What is the best approach for Matchsticks to Square?
Backtracking with pruning is the most commonly used approach. You attempt to place each matchstick into one of four sides while ensuring the side length never exceeds totalSum/4. Sorting the matchsticks in descending order improves pruning efficiency. The complexity is roughly O(4^n) with O(n) recursion space.
Is Matchsticks to Square asked at Google/Amazon/Meta?
Matchsticks to Square is a well-known backtracking and subset partitioning problem that has appeared in interviews at companies like Amazon and Google. It tests recursion, pruning strategies, and sometimes bitmask dynamic programming knowledge.
What data structure is used in Matchsticks to Square?
The problem mainly uses arrays to track matchstick lengths and side sums. Advanced solutions also use bitmasks to represent subsets of matchsticks and dynamic programming tables to cache reachable states.
What is the time complexity of Matchsticks to Square?
The typical backtracking solution runs in O(4^n) time because each matchstick can potentially be placed on any of the four sides. With pruning and sorting, the practical runtime is much lower. The alternative dynamic programming solution using bitmasking runs in O(n · 2^n) time with O(2^n) space.

Ready to solve this problem?

Practice Matchsticks to Square with our built-in code editor and test cases.

Practice on FleetCode