Loading problem...
You are given an array of integers sticks where sticks[i] represents the length of the i-th stick segment. Your goal is to determine whether it is possible to arrange all the sticks to form the perimeter of a perfect square.
The rules are as follows:
A valid square is one where all four sides have exactly the same total length when you sum up the lengths of the sticks assigned to each side.
Return true if you can use all the sticks to construct such a square, and false otherwise.
sticks = [1,1,2,2,2]trueThe total length of all sticks is 1+1+2+2+2 = 8, so each side of the square should be 8/4 = 2. We can form four sides of length 2 as follows: Side 1: [2], Side 2: [2], Side 3: [2], Side 4: [1,1]. All sticks are used exactly once, and each side has total length 2.
sticks = [3,3,3,3,4]falseThe total length is 3+3+3+3+4 = 16, so each side should be 16/4 = 4. However, the stick with length 4 would need to form one complete side, leaving [3,3,3,3] for the remaining three sides. Three sides × length 4 = 12, but the remaining sticks sum to only 12. We would need exactly three sticks of length 4, but we only have one. No valid partition exists.
sticks = [4,4,4,4]trueThe total length is 16, so each side should be 4. We have exactly four sticks, each of length 4, so each stick forms one complete side of the square. This is a perfect match.
Constraints