You are given an integer array matchsticks
where matchsticks[i]
is the length of the i-th
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.
To determine if the matchsticks can form a square, we can follow these steps:
side_length = total_length / 4
.Implementation:
Here’s the implementation in Python:
from typing import List
def makesquare(matchsticks: List[int]) -> bool:
if not matchsticks:
return False
total_length = sum(matchsticks)
if total_length % 4 != 0:
return False
side_length = total_length // 4
matchsticks.sort(reverse=True) # Sorting matchsticks to optimize the backtracking part
sides = [0] * 4
def backtrack(index):
if index == len(matchsticks):
# Check if all sides are equal to required side length
return all(side == side_length for side in sides)
for i in range(4):
if sides[i] + matchsticks[index] <= side_length:
sides[i] += matchsticks[index]
if backtrack(index + 1):
return True
sides[i] -= matchsticks[index]
# If this stick didn't fit in any of the previous sides and the current side is zero, no need to try further.
if sides[i] == 0:
break
return False
return backtrack(0)
Thus, while the worst-case time complexity is high, practical performance is often acceptable due to optimizations from sorting and pruning unnecessary paths.
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?