Skip to content

Commit b2bb293

Browse files
committed
Runtime: 4515 ms (Top 5.02%) | Memory: 38.7 MB (Top 5.74%)
1 parent d3da57b commit b2bb293

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,25 @@
1+
# Runtime: 4515 ms (Top 5.02%) | Memory: 38.7 MB (Top 5.74%)
12
from itertools import permutations
23
class Solution:
34
def isSolvable(self, words: List[str], result: str) -> bool:
45
# we need begins set to track start letters if word is longer than one to not have them as 0
56
begins = {result[0]} if len(result) > 1 else set()
6-
7+
78
# the idea to have counter is to sum repeted letters based on where they are in the word
8-
9+
910
c = Counter()
1011
for w in words:
1112
if len(w) > 1:
1213
begins.add(w[0])
1314
for i,l in enumerate(w[::-1]):
1415
c[l] += 10**i
15-
16+
1617
# we subtract "result" letters from the counter
1718
for i,l in enumerate(result[::-1]):
1819
c[l] -= 10**i
19-
20+
2021
# 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+
2223
# lets split problem into 2 let's check positive letters and negative
2324
pos = []
2425
neg = []
@@ -30,28 +31,28 @@ def isSolvable(self, words: List[str], result: str) -> bool:
3031

3132
if not neg and not pos:
3233
return True
33-
34+
3435
if not neg or not pos:
3536
# False if begins else True this one is needed for words with one letter like words = ["A","B"], result = "A"
3637
return False if begins else True
37-
38+
3839
NN = len(neg)
3940
NP = len(pos)
40-
41+
4142
# we need this one to process permutaion with the smaller number first
4243
# that would optimize speed
4344
if NN > NP:
4445
neg,pos = pos,neg
4546
NN,NP = NP, NN
46-
47+
4748
# we create dict with list of sets of permutations
4849
# keys sum of digit for letter * coefficient
4950
nd = defaultdict(list)
5051
for used in permutations(list(range(10)), NN):
5152
if 0 in used and neg[used.index(0)][0] in begins:
5253
continue
5354
nd[sum(v * used[i] for i,(l,v) in enumerate(neg))].append(set(used))
54-
55+
5556
# same for the other part
5657
# but while we are doing that we check if overlap of digits is missing
5758
for used in permutations(list(range(10)), NP):
@@ -64,4 +65,4 @@ def isSolvable(self, words: List[str], result: str) -> bool:
6465
if not s1 & s2:
6566
return True
6667

67-
return False
68+
return False

0 commit comments

Comments
 (0)