Leetcode 473. 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 form a 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.
Assumptions:
total_length / 4
.import java.util.Arrays;
public class MatchsticksToSquare {
public boolean makesquare(int[] matchsticks) {
int total_length = Arrays.stream(matchsticks).sum();
if (total_length % 4 != 0) {
return false;
}
Arrays.sort(matchsticks); // Sort to optimize - start with larger elements
int side_length = total_length / 4;
int[] sides = new int[4];
return backtrack(matchsticks, sides, matchsticks.length - 1, side_length);
}
private boolean backtrack(int[] matchsticks, int[] sides, int index, int side_length) {
if (index == -1) {
// Check if all sides are equal to side_length
return sides[0] == side_length && sides[1] == side_length &&
sides[2] == side_length && sides[3] == side_length;
}
int matchstick = matchsticks[index];
for (int i = 0; i < 4; i++) {
if (sides[i] + matchstick <= side_length) {
sides[i] += matchstick;
if (backtrack(matchsticks, sides, index - 1, side_length)) {
return true;
}
sides[i] -= matchstick;
}
// If this side is still 0 after the trial, next trials won't be different.
if (sides[i] == 0) break;
}
return false;
}
public static void main(String[] args) {
MatchsticksToSquare solver = new MatchsticksToSquare();
int[] matchsticks = {1, 1, 2, 2, 2};
System.out.println(solver.makesquare(matchsticks)); // Output: true
}
}
While the backtracking step is computationally expensive, it is crucial to check every possible way to form equal sides with the matchsticks. The sorting helps optimize by trying larger elements first, which can help to find a solution early or cut off unsuccessful branches earlier.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?