leetcode 1307 - Verbal Arithmetic Puzzle

https://leetcode.com/problems/verbal-arithmetic-puzzle/

Given an equation, represented by words on left side and the result on right side.

You need to check if the equation is solvable under the following rules:

Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on 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 = [“THIS”,”IS”,”TOO”], result = “FUNNY”
Output: true
Example 4:

Input: words = [“LEET”,”CODE”], result = “POINT”
Output: false

Constraints:

2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
public:
int char_to_int[256];
int int_to_char[10];

bool isSolvable(vector<string>& words, string result) {
for (int i = 0; i < 256; i++)
char_to_int[i] = -1;
for (int i = 0; i < 10; i++)
int_to_char[i] = -1;

string word;
return backtrace(words, 0, 0, 0, 0, result);
}

bool backtrace(vector<string> &words, int i, int k, int num, int sum, string &result) {
if (words[i].size() == k) {
sum += num;
num = 0;
k = 0;
i++;
}

if (i == words.size()) {
return check(sum, result);
}

int c = words[i][k];

for (int n = 0; n <= 9; n++) {
if (n == 0 && k == 0) continue;

if (int_to_char[n] != -1 && int_to_char[n] != c) continue;
if (char_to_int[c] != -1 && char_to_int[c] != n) continue;

int old_c = int_to_char[n];
int old_n = char_to_int[c];

int_to_char[n] = c;
char_to_int[c] = n;

if (backtrace(words, i, k+1, num * 10 + n, sum, result))
return true;

int_to_char[n] = old_c;
char_to_int[c] = old_n;
}

return false;
}

bool check(int sum, string &result) {
if (result.empty()) return false;
int i = result.size() - 1;

do {
if (i < 0) return false;

int n = sum % 10;
sum = sum / 10;

int c = result[i];
if (char_to_int[c] != -1 && char_to_int[c] != n) return false;
if (int_to_char[n] != -1 && int_to_char[n] != c) return false;
i--;
} while (sum);

return i < 0;
}
};