1
+ # Runtime: 4515 ms (Top 5.02%) | Memory: 38.7 MB (Top 5.74%)
1
2
from itertools import permutations
2
3
class Solution :
3
4
def isSolvable (self , words : List [str ], result : str ) -> bool :
4
5
# we need begins set to track start letters if word is longer than one to not have them as 0
5
6
begins = {result [0 ]} if len (result ) > 1 else set ()
6
-
7
+
7
8
# the idea to have counter is to sum repeted letters based on where they are in the word
8
-
9
+
9
10
c = Counter ()
10
11
for w in words :
11
12
if len (w ) > 1 :
12
13
begins .add (w [0 ])
13
14
for i ,l in enumerate (w [::- 1 ]):
14
15
c [l ] += 10 ** i
15
-
16
+
16
17
# we subtract "result" letters from the counter
17
18
for i ,l in enumerate (result [::- 1 ]):
18
19
c [l ] -= 10 ** i
19
-
20
+
20
21
# we get at the end something like that Counter({'S': 1000, 'E': 91, 'R': 10, 'D': 1, 'Y': -1, 'N': -90, 'O': -900, 'M': -9000})
21
-
22
+
22
23
# lets split problem into 2 let's check positive letters and negative
23
24
pos = []
24
25
neg = []
@@ -30,28 +31,28 @@ def isSolvable(self, words: List[str], result: str) -> bool:
30
31
31
32
if not neg and not pos :
32
33
return True
33
-
34
+
34
35
if not neg or not pos :
35
36
# False if begins else True this one is needed for words with one letter like words = ["A","B"], result = "A"
36
37
return False if begins else True
37
-
38
+
38
39
NN = len (neg )
39
40
NP = len (pos )
40
-
41
+
41
42
# we need this one to process permutaion with the smaller number first
42
43
# that would optimize speed
43
44
if NN > NP :
44
45
neg ,pos = pos ,neg
45
46
NN ,NP = NP , NN
46
-
47
+
47
48
# we create dict with list of sets of permutations
48
49
# keys sum of digit for letter * coefficient
49
50
nd = defaultdict (list )
50
51
for used in permutations (list (range (10 )), NN ):
51
52
if 0 in used and neg [used .index (0 )][0 ] in begins :
52
53
continue
53
54
nd [sum (v * used [i ] for i ,(l ,v ) in enumerate (neg ))].append (set (used ))
54
-
55
+
55
56
# same for the other part
56
57
# but while we are doing that we check if overlap of digits is missing
57
58
for used in permutations (list (range (10 )), NP ):
@@ -64,4 +65,4 @@ def isSolvable(self, words: List[str], result: str) -> bool:
64
65
if not s1 & s2 :
65
66
return True
66
67
67
- return False
68
+ return False
0 commit comments