> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/473-matchsticks-to-square.md).

# 473 Matchsticks to Square

Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used**exactly**one time.

Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.

**Example 1:**

```
Input:
 [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:
 [3,3,3,3,4]

Output:
 false


Explanation:
 You cannot find a way to form a square with all the matchsticks.
```

**Note:**

1. The length sum of the given matchsticks is in the range of 0 to 10^9.
2. The length of the given matchstick array will not exceed 15.

## Approach 1: Brute Force \[TLE]

**The Idea:** Abstractly, this problem is equivalent to the partition problem, which aims to determine whether a multi-set can be partitioned into 2 groups, where the sums are the same. In this problem, every match stick has the option of following into 1 or 4 groups, and each group (which sums up to the perimeter length of one side) should add up to one of the respective sides (sum/4). We can perform a few checks first, like identifying that the total sum should some factor of 4, and that no match stick is greater than the greatest possible length it could be (sum/4). Sorting additionally ensures that we converge to a solution faster.![](/files/-LoJIphxrAuemZdUn8GL)

**Complexity:** O(n\*4^n) time and O(n) space

```python
class Solution:
    def makesquare(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        sum_nums = sum(nums)
        if sum_nums % 4 != 0 or not nums:
            return False

        target_len = sum_nums / 4
        nums.sort(reverse=True)

        if nums[-1] > target_len:
            return False

        def dfs(target, groups, index):
            if index == len(nums):
                if all([g == target for g in groups]):
                    return True
                return False

            for j in range(len(groups)):
                num = nums[index]
                if groups[j] + num > target:
                    continue
                groups[j] += num
                if dfs(target, groups, index + 1):
                    return True
                groups[j] -= num

            return False

        return dfs(target_len, [0] * 4, 0)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/473-matchsticks-to-square.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
