1. Permutation Library Generator with Full Eval
Intuition
Extract all U unique characters. Generate all permutations of length U from digits [0..9]. For each permutation, construct candidate mapping, check leading zero conditions, compute number values, and check if val(w1) + val(w2) == val(res).
When to apply: Baseline approach in Python/C++ utilizing itertools.permutations or std::next_permutation.
Algorithm
- Extract list of unique characters
chars. - Generate all permutations of digits 0..9 of length
chars.length. - For each permutation, assign digits to characters.
- If leading characters map to 0, continue.
- If
num(word1) + num(word2) == num(result), return valid mapping.
#include <iostream>#include <vector>#include <string>#include <unordered_map>#include <unordered_set>#include <algorithm>#include <numeric> using namespace std; class Solution { long long getVal(const string& w, const unordered_map<char, int>& map) { long long val = 0; for (char c : w) val = val * 10 + map.at(c); return val; } public: bool solveCryptarithm(string w1, string w2, string res, unordered_map<char, int>& result) { unordered_set<char> charSet; for (char c : w1) charSet.insert(c); for (char c : w2) charSet.insert(c); for (char c : res) charSet.insert(c); if (charSet.size() > 10) return false; vector<char> chars(charSet.begin(), charSet.end()); int u = chars.size(); vector<int> digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // Check all permutations do { unordered_map<char, int> map; for (int i = 0; i < u; i++) map[chars[i]] = digits[i]; if (map[w1[0]] == 0 || map[w2[0]] == 0 || map[res[0]] == 0) continue; if (getVal(w1, map) + getVal(w2, map) == getVal(res, map)) { result = map; return true; } } while (next_permutation(digits.begin(), digits.end())); return false; }}; int main() { Solution sol; unordered_map<char, int> res; if (sol.solveCryptarithm("SEND", "MORE", "MONEY", res)) { for (auto p : res) cout << p.first << ": " << p.second << " "; cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(P(10, U) * L)— P(10, U) is 10! / (10 - U)!. For U = 8 (like SEND MORE MONEY), P(10, 8) = 1,814,400 permutations. L is word length. - Space complexity:
O(U)— Stores unique characters and permutation buffer.