Skip to main content

Matchsticks to Square

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Backtracking
Recursion

You are given matchsticks, where each integer represents the length of one matchstick. Matchsticks may be arranged end to end, but they cannot be broken, and every matchstick must be used exactly once.

Determine whether the matchsticks can form a square: four sides with equal total length. Return true if such an arrangement exists, or false otherwise.

Example 1:

Input: matchsticks = [1,2,3,4,5,6,7,8]
Output: true
Explanation: The sticks can be grouped as (1,8), (2,7), (3,6), and (4,5), giving four sides of length 9.

Example 2:

Input: matchsticks = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,6]
Output: false
Explanation: The total length is 20, so each side would need length 5, but one matchstick already has length 6 and cannot fit on any side.

Example 3:

Input: matchsticks = [3,3,3,3,4,4,4,4]
Output: true
Explanation: Pairing one stick of length 3 with one stick of length 4 on each side produces four sides of length 7.

Constraints:

  • 4 <= matchsticks.length <= 15
  • 1 <= matchsticks[i] <= 10^8
  • The sum of all values in matchsticks is at most 2 * 10^8
  • Each value in matchsticks is an integer

Need help or want more practice?

Practise in an interviewGet AI Coach help