Problem Statement in English
You’re given a 0-indexed array of strings words and a 0-indexed array of integers weights of length 26, where weights[i] is the weight of the ith letter. The weight of a string is the sum of the weights of its letters.
Return a string res of the same length as words where res[i] is the letter that corresponds to the weight of words[i] modulo 26. The letter corresponding to a weight w follows the pattern 0 -> z, 1 -> y, …, 25 -> a.
Approach
This is about implementation. We can create a mapping of weights to letters and then calculate the weight of each word in words using the weights array. Finally, we can find the corresponding letter for each word’s weight modulo 26 and build the result string.
And we’re done!
Solution in Python
class Solution:
def mapWordWeights(self, words: List[str], weights: List[int]) -> str:
hm = {i: chr(ord("z") - i) for i in range(26)}
res = []
for word in words:
temp = 0
for l in word:
temp += weights[ord(l) - ord("a")]
res.append(hm[temp % 26])
return "".join(res)
Complexity
Time: $O(n \cdot m)$
where $n$ is the number of words and $m$ is the average length of each word.Space: $O(1)$
We are using a constant amount of space to store the mapping and the result string.
And we are done.