3838. Weighted Word Mapping
- Array
- String
- Hash Table
TIME
O(L) over all characters
SPACE
O(w) for the output
Intuition
Each word maps to a single character through three direct steps: sum its letter weights, reduce modulo 26, then translate that index to a letter in reverse alphabetical order. There is nothing to optimize, just apply the rule to every word and concatenate.
Approach
- For each word, sum
weights[ord(ch) - ord('a')]over its characters. - Reduce the sum modulo 26 to get an index
rin[0, 25]. - Map
rto a letter in reverse order:0 -> 'z', ...,25 -> 'a', i.e.chr(ord('z') - r). - Concatenate all mapped characters in word order and return the result.
Complexity
- Time: O(L), where
Lis the total number of characters across all words - Space: O(w), the output string, one character per word
Edge Cases
- Weight sum exactly divisible by 26 -> index
0->'z' - Single-character word -> just that letter's weight modulo 26
- Single word -> output is a one-character string
Code
from typing import List
class Solution:
def weightedWordMapping(self, words: List[str], weights: List[int]) -> str:
"""
3838. Weighted Word Mapping
Time: O(L) over all characters
Space: O(w) for the output
"""
result = []
for word in words:
total = sum(weights[ord(ch) - ord('a')] for ch in word)
r = total % 26
result.append(chr(ord('z') - r))
return "".join(result)/**
* 3838. Weighted Word Mapping
* Time: O(L) over all characters
* Space: O(w) for the output
*/
class Solution {
public String weightedWordMapping(String[] words, int[] weights) {
StringBuilder result = new StringBuilder();
for (String word : words) {
int total = 0;
for (int i = 0; i < word.length(); i++) {
total += weights[word.charAt(i) - 'a'];
}
int r = total % 26;
result.append((char) ('z' - r));
}
return result.toString();
}
}