3838. Weighted Word Mapping
UnknownView on LeetCode
Time: O(total characters)
Space: O(1)
Advertisement
Intuition
Each word is mapped independently. Add the weight of every letter, reduce modulo 26, then convert that residue to a single output character using the reverse-alphabet formula 25 - sum. The only work per word is one pass over its characters plus constant-time modular arithmetic.
Algorithm
- 1Initialize an empty result string.
- 2For each word, set sum = 0.
- 3For each character c in the word, add weights[c - 'a'] to sum and take sum modulo 26.
- 4Append the character (char)('a' + (25 - sum)) to the result.
- 5Return the built string after all words are processed.
Example Walkthrough
Input: words = ["a", "b"], weights = [1,2,...,26]
- 1.For "a": sum = weights[0] = 1, so mapped index is 25 - 1 = 24 -> 'y'.
- 2.For "b": sum = weights[1] = 2, so mapped index is 25 - 2 = 23 -> 'x'.
- 3.Concatenate the mapped letters in input order.
Output: "yx"
Common Pitfalls
- •Apply modulo 26 after every addition to keep the sum in range.
- •The output index is 25 - sum, not sum itself.
- •weights[i] corresponds to the i-th lowercase letter starting from 'a'.
3838.cs
C#
// Approach: For each word, sum the per-letter weights modulo 26, then map that value to a
// character with index 25 - sum (equivalently the reverse-alphabet position).
// Time: O(total characters) Space: O(1) excluding output
public class Solution
{
public string MapWordWeights(string[] words, int[] weights)
{
var ans = new StringBuilder();
foreach (var w in words)
{
int s = 0;
foreach (char c in w)
s = (s + weights[c - 'a']) % 26;
ans.Append((char)('a' + (25 - s)));
}
return ans.ToString();
}
}Advertisement
Was this solution helpful?