Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Verbal Arithmetic Puzzle

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1307" 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

Given an equation, represented by words on the left side and the result on the right side. You need to check if the equation is solvable under the following rules: Each character is decoded as one digit (0 - 9). No two characters can map to the same digit. Each words[i] and result are decoded as one number without leading zeros. Sum of numbers on the left side (words) will equal to the number on the right side (result). Return true if the equation is solvable, otherwise return false. Example 1: Input: words = ["SEND","MORE"], result = "MONEY" Output: true Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2' Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652 Example 2: Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY" Output: true Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4 Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214 Example 3: Input: words = ["LEET","CODE"], result = "POINT" Output: false Explanation: There is no possible mapping to satisfy the equation, so we return false. Note that two different characters cannot map to the same digit. Constraints: 2 <= words.length <= 5 1 <= words[i].length, result.length <= 7 words[i], result contain only uppercase English letters. The number of different characters used in the expression is at most 10.

Explanation

Here's the breakdown of the solution:

  • Backtracking with Constraint Satisfaction: The solution uses a backtracking algorithm to explore possible digit assignments to the characters. At each step, it checks if the current assignment violates the constraints (no two characters map to the same digit, and no leading zeros).

  • Optimization with Pruning: The code optimizes the search by calculating the contribution of each character to the overall sum. It then checks if the partial sum at any point exceeds the corresponding prefix of the result, allowing early termination of unproductive branches.

  • Leading Zero Check: Before evaluating a word or the result, the code checks for leading zeros, immediately returning false if a word starts with a mapped zero.

  • Time & Space Complexity: O(10!), O(10) - where the 10! represents the worst-case scenario of assigning all 10 digits to characters, and O(10) represents the space required to store the mapping and used digits.

Code

    class Solution:
    def isSolvable(self, words: list[str], result: str) -> bool:
        chars = set()
        for word in words:
            for char in word:
                chars.add(char)
        for char in result:
            chars.add(char)

        chars = list(chars)
        n = len(chars)
        mapping = {}
        used = [False] * 10

        def leading_zero(word, mapping):
            if len(word) > 1 and word[0] in mapping and mapping[word[0]] == 0:
                return True
            return False

        def calculate_value(word, mapping):
            if leading_zero(word, mapping):
                return -1

            value = 0
            for char in word:
                value = value * 10 + mapping[char]
            return value

        def backtrack(index):
            if index == n:
                total_sum = 0
                for word in words:
                    val = calculate_value(word, mapping)
                    if val == -1:
                        return False
                    total_sum += val

                result_val = calculate_value(result, mapping)

                if result_val == -1:
                    return False

                return total_sum == result_val

            char = chars[index]
            for digit in range(10):
                if not used[digit]:
                    mapping[char] = digit
                    used[digit] = True

                    if backtrack(index + 1):
                        return True

                    used[digit] = False
                    del mapping[char]

            return False

        return backtrack(0)

More from this blog

C

Chatmagic blog

2894 posts