3838. Weighted Word Mapping
Description
You are given an array of strings words, where each string represents a word containing lowercase English letters.
You are also given an integer array weights of length 26, where weights[i] represents the weight of the ith lowercase English letter.
The weight of a word is defined as the sum of the weights of its characters.
For each word, take its weight modulo 26 and map the result to a lowercase English letter using reverse alphabetical order (0 -> 'z', 1 -> 'y', ..., 25 -> 'a').
Return a string formed by concatenating the mapped characters for all words in order.
Example 1:
Input: words = ["abcd","def","xyz"], weights = [5,3,12,14,1,2,3,2,10,6,6,9,7,8,7,10,8,9,6,9,9,8,3,7,7,2]
Output: "rij"
Explanation:
- The weight of
"abcd"is5 + 3 + 12 + 14 = 34. The result modulo 26 is34 % 26 = 8, which maps to'r'. - The weight of
"def"is14 + 1 + 2 = 17. The result modulo 26 is17 % 26 = 17, which maps to'i'. - The weight of
"xyz"is7 + 7 + 2 = 16. The result modulo 26 is16 % 26 = 16, which maps to'j'.
Thus, the string formed by concatenating the mapped characters is "rij".
Example 2:
Input: words = ["a","b","c"], weights = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
Output: "yyy"
Explanation:
Each word has weight 1. The result modulo 26 is 1 % 26 = 1, which maps to 'y'.
Thus, the string formed by concatenating the mapped characters is "yyy".
Example 3:
Input: words = ["abcd"], weights = [7,5,3,4,3,5,4,9,4,2,2,7,10,2,5,10,6,1,2,2,4,1,3,4,4,5]
Output: "g"
Explanation:
The weight of "abcd" is 7 + 5 + 3 + 4 = 19. The result modulo 26 is 19 % 26 = 19, which maps to 'g'.
Thus, the string formed by concatenating the mapped characters is "g".
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 10weights.length == 261 <= weights[i] <= 100words[i]consists of lowercase English letters.
Solutions
Solution 1: Simulation
Thinking
A word's weight is the sum of letter weights, then taken modulo \(26\) and mapped backward through the alphabet. Total length is small, so we follow the definition.
Words do not interact, so no global structure is required.
Sum \(weights[c-'a']\) for each word, reduce modulo \(26\), and map to the letter \(s\bmod 26\) steps back from \(\texttt{z}\).
Concatenate the mapped letters in input order.
We iterate through each word \(w\) in \(\textit{words}\), calculate its weight \(s\), which is the sum of the weights of all characters in the word. Then we calculate \(s\) modulo 26, map the result to a lowercase English letter, and finally concatenate all the mapped characters and return.
The time complexity is \(O(L)\), where \(L\) is the sum of the lengths of all words in \(\textit{words}\). The space complexity is \(O(W)\), where \(W\) is the length of \(\textit{words}\).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |