#3838

Weighted Word Mapping

Easy
ArrayStringSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Sum character weights directly using the weights array and compute the result in a single pass for each word, achieving linear time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty result string.
  2. 2Step 2: For each word, compute the total weight using the weights array.
  3. 3Step 3: Map the total weight modulo 26 to the corresponding character and append to the result.
solution.py6 lines
1def weighted_word_mapping(words, weights):
2    result = ''
3    for word in words:
4        weight_sum = sum(weights[ord(c) - ord('a')] for c in word)
5        result += chr(122 - (weight_sum % 26))
6    return result

Complexity note: Each word is processed in linear time, leading to O(n) overall complexity.

  • 1Mapping weights to characters efficiently reduces complexity.
  • 2Understanding character encoding helps in direct calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.