Verbal Arithmetic Puzzle Problem
Description
LeetCode Problem 1307.
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]andresultare 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 <= 51 <= words[i].length, result.length <= 7words[i], resultcontain only uppercase English letters.- The number of different characters used in the expression is at most
10.
Solution
Approach: Backtracking Column by Column
Trying every assignment of digits to up to 10 letters means up to 10! = 3,628,800 assignments, each checked against the whole equation. We can cut most of them early by doing what we would do on paper: add the columns from right to left, carrying into the next column.
Put result as the last row, and subtract it instead of adding. Walk the columns from the right, and within a column go through the rows one at a time, keeping a balance bal: the carry from the previous column, plus the digits of the words seen so far in this column, minus the digit of result. A word that is too short for this column is skipped.
- If the current letter already has a digit, use it.
- Otherwise try each unused digit for it, recurse, and undo the choice if it fails.
When a column is complete, its balance must end in 0 (bal % 10 == 0): the column's digits add up to the result's digit plus ten times the carry. The rest, bal / 10, is the carry into the next column. After the last column, the balance must be exactly 0. This check fails as soon as a column is wrong, so a bad choice for the low digits is discarded before any higher letter is tried.
The tricky rule is leading zeros: the first letter of a word or of result cannot be 0, but only when the number has more than one digit (a one-letter word may be 0). We collect those first letters up front and never give them the digit 0. For example, ["AB","AC"] with result = "AD" is false: AB + AC = AD means 10 * A + B + C = D, which only works with A = 0.
Complexity: O(10!) time in the worst case, as in any search over the assignments, but the column check prunes almost all of it in practice. O(m) space for the recursion, where m is the total number of letters in the equation.
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
rows = words + [result] # the result row is subtracted
width = max(len(w) for w in rows)
nonzero = {w[0] for w in rows if len(w) > 1} # first letters of multi-digit numbers
digit = {} # letter -> its digit
used = [False] * 10
# Go through the columns from the right, one row at a time. bal is the incoming carry plus the
# digits of the words seen so far in this column, minus the result's digit.
def dfs(col, row, bal):
if col == width:
return bal == 0
if row == len(rows):
# The column is complete: it must end in 0, and the rest carries into the next column.
return bal % 10 == 0 and dfs(col + 1, 0, bal // 10)
w = rows[row]
if col >= len(w):
return dfs(col, row + 1, bal)
sign = -1 if row == len(rows) - 1 else 1
c = w[-1 - col]
if c in digit:
return dfs(col, row + 1, bal + sign * digit[c])
for d in range(1 if c in nonzero else 0, 10):
if not used[d]:
used[d] = True
digit[c] = d
if dfs(col, row + 1, bal + sign * d):
return True
used[d] = False
del digit[c]
return False
return dfs(0, 0, 0)