Matchsticks to Square LeetCode solution in JavaScript

1
var makesquare = function (matchsticks) {
2
const perimeter = matchsticks.reduce((a, b) => a + b, 0);
3
if (perimeter % 4 != 0 || matchsticks.length < 4) return false;
4

5
const sideLen = perimeter / 4;
6
// find a way to divide the array in 4 group of sum side length
7
const sides = new Array(4).fill(0);
8
const len = matchsticks.length;
9
matchsticks.sort((a, b) => b - a);
10

11
const solve = (x = 0) => {
12
if (x == len) {
13
return sides.every((side) => side == sideLen);
14
}
15

16
for (let i = 0; i < 4; i++) {
17
if (sides[i] + matchsticks[x] > sideLen) {
18
continue;
19
}
20
sides[i] += matchsticks[x];
21
if (solve(x + 1)) return true;
22
sides[i] -= matchsticks[x];
23
}
24
return false;
25
};
26
return solve();
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0