#1307

Verbal Arithmetic Puzzle

Hard
ArrayMathStringBacktrackingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n!)
Space
O(1)
O(n)
💡

Intuition

Time O(n!)Space O(n)

Using backtracking with pruning allows us to efficiently explore valid digit assignments while avoiding unnecessary checks. We can eliminate invalid configurations early, which speeds up the process.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a mapping of characters to digits and a set to track used digits.
  2. 2Step 2: Use backtracking to assign digits to characters, ensuring no leading zeros.
  3. 3Step 3: Check if the current assignment satisfies the equation. If it does, return true; if not, backtrack.
solution.py25 lines
1def is_solvable(words, result):
2    unique_chars = set(''.join(words) + result)
3    if len(unique_chars) > 10:
4        return False
5    char_to_digit = {}
6    return backtrack(words, result, char_to_digit, set())
7
8
9def backtrack(words, result, char_to_digit, used_digits):
10    if len(char_to_digit) == len(set(''.join(words) + result)):
11        words_sum = sum(int(''.join(str(char_to_digit[c]) for c in word)) for word in words)
12        result_num = int(''.join(str(char_to_digit[c]) for c in result))
13        return words_sum == result_num
14    for digit in range(10):
15        if digit in used_digits:
16            continue
17        for char in set(''.join(words) + result):
18            if char not in char_to_digit:
19                char_to_digit[char] = digit
20                used_digits.add(digit)
21                if backtrack(words, result, char_to_digit, used_digits):
22                    return True
23                del char_to_digit[char]
24                used_digits.remove(digit)
25    return False

Complexity note: The time complexity is O(n!) due to the factorial growth of permutations for digit assignments, but pruning reduces the number of checks significantly.

  • 1Each character must map to a unique digit.
  • 2Leading zeros are not allowed for any word.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.