Matchsticks to Square

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.

30:00

Matchsticks to Square
medium
Free written solution
Topics
Companies

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
Constraints:
  • 1≤matchsticks.length≤151 \leq \text{matchsticks.length} \leq 15

  • 1≤matchsticks[i]≤1081 \leq \text{matchsticks}[i] \leq 10^8

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"matchsticks":[1,1,2,2,2]}

Every stick must be used, so the square's perimeter is the sum of all 5 sticks.

????perimeter 0

sticks

0

1

-

1

1

-

2

2

-

3

2

-

4

2

-

green: just laidred dashes: overflows or removedgrey dashes: same as previous side, skipped
Variables
VariableValue
total0
DepthFunction Call
Stack empty
0/22