632. Letter Sum Puzzle

Hard7.5 points estimatedStringBacktrackingMaths3 hints

A letter-sum puzzle is an addition in which every digit has been replaced by a capital letter. You are given the addends words and the total result. Decide whether digits can be assigned to the letters so that the sum of the numbers written by words equals the number written by result.

The assignment must follow three rules: every letter gets one digit from 0 to 9 and the same letter always gets the same digit; different letters get different digits; and a number of two or more letters must not start with the digit 0 (a number made of a single letter may be 0).

Return true if such an assignment exists, otherwise false.

Example 1

Input:
words = ["TWO","TWO"], result = "FOUR"
Output:
true
Explanation:

With T=7, W=3, O=4, F=1, U=6, R=8 we get 734 + 734 = 1468.

Example 2

Input:
words = ["AB","BA"], result = "CC"
Output:
true
Explanation:

With A=1, B=2, C=3: 12 + 21 = 33.

Example 3

Input:
words = ["A","B"], result = "AB"
Output:
false
Explanation:

The sum would need 9A = 0, so A = 0, but A is the first letter of the two-letter number AB, which may not start with 0.

Constraints

  • 1 ≤ words.length ≤ 5
  • 1 ≤ words[i].length ≤ 7 and 1 ≤ result.length ≤ 8
  • All strings consist of capital letters and, together, use at most 10 different letters in the tests (more than 10 is always false).

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(10! / (10 - u)!) in the worst case, far less with pruning
Space
O(u + columns)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…