Verbal Arithmetic Puzzle - Problem
Welcome to the fascinating world of cryptarithmetic puzzles! ๐งฉ
You're given a verbal arithmetic equation where letters represent digits. Your mission is to determine if there's a way to assign unique digits (0-9) to each letter such that the mathematical equation holds true.
The Rules:
- Each unique character maps to exactly one digit (0-9)
- No two characters can represent the same digit
- No word can have leading zeros (unless it's a single digit)
- The sum of all words on the left must equal the result on the right
Example: SEND + MORE = MONEY
This famous puzzle has the solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2
So: 9567 + 1085 = 10652 โ
Return true if a valid digit assignment exists, false otherwise.
Input & Output
example_1.py โ Classic SEND + MORE = MONEY
$
Input:
words = ["SEND", "MORE"], result = "MONEY"
โบ
Output:
true
๐ก Note:
One valid solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2. This gives us: 9567 + 1085 = 10652, which is correct.
example_2.py โ Simple Addition
$
Input:
words = ["SIX", "SEVEN", "SEVEN"], result = "TWENTY"
โบ
Output:
true
๐ก Note:
One valid solution exists: S=6, I=5, X=0, E=8, V=7, N=2, T=1, W=3, Y=4. This gives us: 650 + 68782 + 68782 = 138214.
example_3.py โ Impossible Case
$
Input:
words = ["LEET", "CODE"], result = "POINT"
โบ
Output:
false
๐ก Note:
No valid digit assignment exists that satisfies all constraints. The equation cannot be made true with unique digit mappings.
Visualization
Tap to expand
Understanding the Visualization
1
Intelligence Gathering
Identify all unique letters in the message and note which ones can't be zero (first letters of multi-digit numbers)
2
Systematic Decryption
Try assigning digits to letters one by one, immediately discarding impossible combinations
3
Constraint Checking
Ensure each digit is used only once and no word starts with zero
4
Message Verification
When all letters are assigned, check if the mathematical equation holds true
Key Takeaway
๐ฏ Key Insight: Backtracking with constraint propagation transforms an intractable brute force problem into an efficient search by eliminating impossible assignments early in the decision tree.
Time & Space Complexity
Time Complexity
O(10!)
We try all permutations of 10 digits for unique characters (worst case 10 unique chars)
โ Linear Growth
Space Complexity
O(k)
Where k is the number of unique characters for storing the mapping
โ Linear Space
Constraints
- 2 โค words.length โค 5
- 1 โค words[i].length, result.length โค 7
- words[i] and result contain only uppercase English letters
- The number of different characters used in the expression is at most 10
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code