Matchsticks to Square
Given an array matchsticks where each value is a matchstick length, determine whether you can use every matchstick exactly once, without breaking any, to form a square (four sides of equal length).
Open official problem prompt ↗Decide whether the sticks can be split into four groups that each sum to one quarter of the total length.
Like sorting nails into four cups so each cup weighs the same; you drop each nail into a cup that still has room and backtrack if you get stuck.
- Input
- matchsticks = [1,1,2,2,2]
- Output
- true
- Why
- Total is 8, so each side must be 2: sides are 2, 2, 1+1, and 2 — every stick used exactly once.
1 <= matchsticks.length <= 151 <= matchsticks[i] <= 10^8The array is used entirely; sticks cannot be broken