Back to blog
Jul 07, 2024
4 min read

Weighted Word Mapping

Calculate the sum of alphabetical weights for the first k characters of a string.

Difficulty: Easy | Acceptance: 85.70% | Paid: No Topics: Array, String, Simulation

You are given a string s consisting of lowercase English letters and an integer k.

The weight of a character is defined as its position in the English alphabet (1-indexed). For example, ‘a’ has a weight of 1, ‘b’ has a weight of 2, …, and ‘z’ has a weight of 26.

Return the sum of the weights of the first k characters in the string s.

Examples

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” is 5 + 3 + 12 + 14 = 34. The result modulo 26 is 34 % 26 = 8, which maps to ‘r’.

The weight of “def” is 14 + 1 + 2 = 17. The result modulo 26 is 17 % 26 = 17, which maps to ‘i’.

The weight of “xyz” is 7 + 7 + 2 = 16. The result modulo 26 is 16 % 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"

Constraints

- 1 <= words.length <= 100
- 1 <= words[i].length <= 10
- weights.length == 26
- 1 <= weights[i] <= 100
- words[i] consists of lowercase English letters.

Iterative Simulation

Intuition We iterate through the first k characters of the string, calculate the weight for each character based on its ASCII value, and accumulate the sum.

Steps

  • Initialize a variable total to 0.
  • Loop from index 0 to k - 1.
  • For each character c at index i, calculate its weight using the formula c - 'a' + 1.
  • Add the calculated weight to total.
  • Return total.
python
class Solution:
    def getWeightedSum(self, s: str, k: int) -&gt; int:
        total = 0
        for i in range(k):
            # ord('a') is 97, so ord(c) - 96 gives the 1-based index
            total += ord(s[i]) - 96
        return total

Complexity

  • Time: O(k) — We iterate through the first k characters.
  • Space: O(1) — We only use a constant amount of extra space.
  • Notes: This is the most efficient approach for a single query.

Functional Approach

Intuition Utilize built-in functional programming constructs like map, reduce, or sum to transform the string slice into a sum of weights in a declarative style.

Steps

  • Slice the string to get the first k characters.
  • Map each character to its corresponding weight.
  • Reduce or sum the resulting array of weights.
python
class Solution:
    def getWeightedSum(self, s: str, k: int) -&gt; int:
        # Using generator expression for efficiency
        return sum(ord(c) - 96 for c in s[:k])

Complexity

  • Time: O(k) — We still need to process k elements.
  • Space: O(k) or O(1) — Depending on the language implementation (e.g., s.split('') in JS creates an array).
  • Notes: More concise but may have slightly higher constant factors or memory overhead due to intermediate collections.

Lookup Table

Intuition Precompute the weights of all 26 letters in an array. This avoids repeated ASCII arithmetic, trading a tiny bit of memory for potentially faster lookups in some architectures.

Steps

  • Create an array weights of size 26 where weights[i] = i + 1.
  • Iterate through the first k characters.
  • For each character c, use weights[c - 'a'] to get its weight.
  • Accumulate the sum.
python
class Solution:
    def getWeightedSum(self, s: str, k: int) -&gt; int:
        # Precomputed weights: index 0 -&gt; 'a' (1), index 1 -&gt; 'b' (2), etc.
        weights = [i + 1 for i in range(26)]
        total = 0
        for i in range(k):
            total += weights[ord(s[i]) - 97]
        return total

Complexity

  • Time: O(k) — Iteration is still linear.
  • Space: O(1) — The lookup table is a fixed size of 26, which is constant space.
  • Notes: Useful if the weight calculation logic is complex or non-arithmetic, but for simple ASCII offset, the arithmetic approach is usually preferred.