Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Matchsticks to Square

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "473" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 make one 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. Example 1: Input: matchsticks = [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. Example 2: Input: matchsticks = [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks. Constraints: 1 <= matchsticks.length <= 15 1 <= matchsticks[i] <= 108

Explanation

Here's an efficient solution to determine if matchsticks can form a square, along with explanations and complexity analysis:

  • Calculate the Target Side Length: First, calculate the perimeter by summing all matchstick lengths. If the perimeter isn't divisible by 4, it's impossible to form a square. The target side length is perimeter / 4.
  • Backtracking with Pruning: Use backtracking to try assigning matchsticks to each side of the square. Sort the matchsticks in descending order. This is a crucial optimization (pruning): trying longer sticks first allows the algorithm to fail faster when a solution is not possible.
  • Bitmask to Track Used Sticks: Use a bitmask to represent which matchsticks have been used. This avoids redundant calculations and makes the solution more efficient.

  • Runtime Complexity: O(4n), where n is the number of matchsticks (due to backtracking). Sorting contributes O(n log n), but it's dominated by the backtracking. Storage Complexity: O(n), primarily due to the recursion depth and the matchsticks array.

Code

    def makesquare(matchsticks):
    """
    Determines if the given matchsticks can form a square.

    Args:
        matchsticks: A list of integers representing the lengths of the matchsticks.

    Returns:
        True if the matchsticks can form a square, False otherwise.
    """
    perimeter = sum(matchsticks)
    if perimeter % 4 != 0:
        return False

    side_length = perimeter // 4
    if any(stick > side_length for stick in matchsticks):
        return False

    matchsticks.sort(reverse=True)
    n = len(matchsticks)
    sides = [0] * 4

    def backtrack(index):
        if index == n:
            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]  # Backtrack

        return False

    return backtrack(0)

More from this blog

C

Chatmagic blog

2894 posts