Matchsticks to Square

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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.

Examples

Example 1:

Input: matchsticks = [1,1,2,2,2]

Output: true

Explanation: The total length is 8, so each side must be 2. We can form four sides: [2], [2], [2], [1,1].

Example 2:

Input: matchsticks = [3,3,3,3,4]

Output: false

Explanation: The total length is 16, so each side must be 4. The stick of length 4 fills one side, but the remaining sticks of length 3 cannot form three sides of length 4.

Example 3:

Input: matchsticks = [1,2,3,4,5,6,7]

Output: true

Explanation: The total length is 28, so each side must be 7. We can form: [7], [6,1], [5,2], [4,3].

Constraints

  • 1 <= matchsticks.length <= 15
  • 1 <= matchsticks[i] <= 10^8
Source: Backtracking pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle