KatInterview

473. Matchsticks to Square

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Backtracking with Pruning

This problem asks if we can partition the matchsticks array into four subsets with equal sums. This is a classic partition problem, well-suited for a backtracking (depth-first search) approach, especially given the small constraint matchsticks.length <= 15.

Solution

Matchsticks to Square in Python

class Solution:
    def makesquare(self, matchsticks: List[int]) -> bool:
        if not matchsticks or len(matchsticks) < 4:
            return False

        perimeter = sum(matchsticks)
        if perimeter % 4 != 0:
            return False

        side_length = perimeter // 4
        sides = [0] * 4

        # Sort descending. This is a crucial optimization.
        # It makes the algorithm fail faster on impossible branches.
        matchsticks.sort(reverse=True)
        
        # Optional early exit: if the largest matchstick is bigger than a side
        if matchsticks[0] > side_length:
            return False

        def backtrack(index: int) -> bool:
            # Base case: if we have placed all matchsticks, we are done.
            if index == len(matchsticks):
                # No need to check sides sum, if we got here, it's a valid solution
                return True

            # Try to place the current matchstick on each of the 4 sides
            for i in range(4):
                # If adding the stick exceeds the side length, this side is not an option
                if sides[i] + matchsticks[index] > side_length:
                    continue
                
                # Pruning: if the previous side had the same length and we didn't use it,
                # don't try this side either. This avoids redundant computations from permutations.
                if i > 0 and sides[i] == sides[i - 1]:
                    continue

                # Place the stick
                sides[i] += matchsticks[index]

                # Recurse
                if backtrack(index + 1):
                    return True

                # Backtrack
                sides[i] -= matchsticks[index]
            
            # If we tried all sides and none worked, this path is a failure.
            return False

        return backtrack(0)

Matchsticks to Square in Java

class Solution {
    public boolean makesquare(int[] matchsticks) {
        if (matchsticks == null || matchsticks.length < 4) {
            return false;
        }

        long perimeter = 0;
        for (int len : matchsticks) {
            perimeter += len;
        }

        if (perimeter % 4 != 0) {
            return false;
        }

        long sideLength = perimeter / 4;

        // Sort the array. We will backtrack from the largest to the smallest element.
        // This is a crucial optimization to fail faster.
        Arrays.sort(matchsticks);
        
        return backtrack(matchsticks.length - 1, matchsticks, new long[4], sideLength);
    }

    private boolean backtrack(int index, int[] matchsticks, long[] sides, long sideLength) {
        // Base case: If we have placed all matchsticks (processed from n-1 down to 0).
        if (index < 0) {
            return true;
        }

        // Try to place the current matchstick (matchsticks[index]) on each of the 4 sides.
        for (int i = 0; i < 4; i++) {
            // If adding the stick exceeds the side length, this side is not an option.
            if (sides[i] + matchsticks[index] > sideLength) {
                continue;
            }

            // Pruning: if the previous side had the same length and we didn't use it,
            // don't try this side either. This avoids redundant computations from permutations.
            if (i > 0 && sides[i] == sides[i - 1]) {
                continue;
            }

            // Place the stick
            sides[i] += matchsticks[index];

            // Recurse with the next smaller stick
            if (backtrack(index - 1, matchsticks, sides, sideLength)) {
                return true;
            }

            // Backtrack
            sides[i] -= matchsticks[index];
        }

        // If we tried all sides and none worked, this path is a failure.
        return false;
    }
}

Matchsticks to Square in C++

class Solution {
public:
    bool makesquare(vector<int>& matchsticks) {
        if (matchsticks.size() < 4) {
            return false;
        }

        long long perimeter = 0;
        for (int len : matchsticks) {
            perimeter += len;
        }

        if (perimeter % 4 != 0) {
            return false;
        }

        long long side_length = perimeter / 4;
        vector<long long> sides(4, 0);

        // Sort descending. This is a crucial optimization.
        // It makes the algorithm fail faster on impossible branches.
        sort(matchsticks.rbegin(), matchsticks.rend());

        return backtrack(0, matchsticks, sides, side_length);
    }

private:
    bool backtrack(int index, const vector<int>& matchsticks, vector<long long>& sides, long long side_length) {
        // Base case: if we have placed all matchsticks, we are done.
        if (index == matchsticks.size()) {
            return true;
        }

        // Try to place the current matchstick (matchsticks[index]) on each of the 4 sides.
        for (int i = 0; i < 4; ++i) {
            // If adding the stick exceeds the side length, this side is not an option.
            if (sides[i] + matchsticks[index] > side_length) {
                continue;
            }
            
            // Pruning: if the previous side had the same length and we didn't use it,
            // don't try this side either. This avoids redundant computations from permutations.
            if (i > 0 && sides[i] == sides[i - 1]) {
                continue;
            }

            // Place the stick
            sides[i] += matchsticks[index];

            // Recurse
            if (backtrack(index + 1, matchsticks, sides, side_length)) {
                return true;
            }

            // Backtrack
            sides[i] -= matchsticks[index];
        }

        // If we tried all sides and none worked, this path is a failure.
        return false;
    }
};

Matchsticks to Square in TypeScript

function makesquare(matchsticks: number[]): boolean {
    if (matchsticks.length < 4) {
        return false;
    }

    const perimeter = matchsticks.reduce((sum, len) => sum + len, 0);

    if (perimeter % 4 !== 0) {
        return false;
    }

    const sideLength = perimeter / 4;
    const sides = new Array(4).fill(0);

    // Sort descending. This is a crucial optimization.
    // It makes the algorithm fail faster on impossible branches.
    matchsticks.sort((a, b) => b - a);

    function backtrack(index: number): boolean {
        // Base case: if we have placed all matchsticks, we are done.
        if (index === matchsticks.length) {
            return true;
        }

        // Try to place the current matchstick on each of the 4 sides.
        for (let i = 0; i < 4; i++) {
            // If adding the stick exceeds the side length, this side is not an option.
            if (sides[i] + matchsticks[index] > sideLength) {
                continue;
            }

            // Pruning: if the previous side had the same length and we didn't use it,
            // don't try this side either. This avoids redundant computations from permutations.
            if (i > 0 && sides[i] === sides[i - 1]) {
                continue;
            }

            // Place the stick
            sides[i] += matchsticks[index];

            // Recurse
            if (backtrack(index + 1)) {
                return true;
            }

            // Backtrack
            sides[i] -= matchsticks[index];
        }

        // If we tried all sides and none worked, this path is a failure.
        return false;
    }

    return backtrack(0);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.