LeetCode 3838: Weighted Word Mapping – Java Solution Explained with Multiple Approaches

Learn How to Convert Weighted Words into Encoded Characters Using Hashing, Modular Arithmetic, and Optimized Character Mapping

Krishna Shrivastava
67 views
LinkedInGithubX
0
0
LeetCode 3838: Weighted Word Mapping – Java Solution Explained with Multiple Approaches
Listen to articleAudio version
Ad
Advertisement

Introduction

LeetCode 3838, Weighted Word Mapping, is a straightforward yet interesting problem that combines several fundamental programming concepts:

  1. Character mapping
  2. Hashing
  3. Modular arithmetic
  4. String processing
  5. Optimization techniques

At first glance, the problem appears to be a simple implementation exercise. However, it provides a great opportunity to discuss different approaches and understand how fixed-size alphabets can help us write more efficient code.

In this article, we'll explore the problem step-by-step, discuss multiple solutions, perform a dry run, and analyze the complexity of each approach.

Problem Link -: Weighted Word Mapping

Problem Statement

You are given:

  1. An array of strings words
  2. An integer array weights of length 26

Each index in the weights array corresponds to a lowercase English letter.

For every word:

  1. Calculate the sum of character weights.
  2. Take the result modulo 26.
  3. Convert the modulo result into a letter using reverse alphabetical order:
0 → z
1 → y
2 → x
...
25 → a

Return a string formed by concatenating all mapped letters.

Example

Input

words = ["abcd", "def", "xyz"]

Output

"rij"

Explanation

For the word "abcd":

a = 5
b = 3
c = 12
d = 14

Total Weight = 34

34 % 26 = 8

8 → r

For "def":

14 + 1 + 2 = 17

17 % 26 = 17

17 → i

For "xyz":

7 + 7 + 2 = 16

16 % 26 = 16

16 → j

Final Answer:

"rij"

Understanding the Core Idea

The problem consists of three independent operations:

Step 1: Calculate Word Weight

For each word:

Weight(word) = Sum of character weights

Example:

abc

a = 5
b = 3
c = 12

Weight = 20

Step 2: Apply Modulo 26

The problem requires:

Weight % 26

This guarantees that the result always lies between:

0 and 25

Step 3: Reverse Alphabet Mapping

Unlike normal alphabet indexing:

0 → a
1 → b
2 → c

the problem uses:

0 → z
1 → y
2 → x
...
25 → a

This reverse mapping generates the final encoded character.

Approach 1: HashMap-Based Solution

Intuition

Create:

Map 1

Character → Weight

Example:

a → 5
b → 3
c → 12

Map 2

Modulo Value → Character

Example:

0 → z
1 → y
2 → x

Then process each word and build the answer.

Java Implementation

class Solution {
public String mapWordWeights(String[] words, int[] weights) {

HashMap<Character,Integer> weightMap = new HashMap<>();
HashMap<Integer,Character> reverseMap = new HashMap<>();

for(int i = 0; i < 26; i++) {

char letter = (char)('a' + i);
char reverseLetter = (char)('z' - i);

weightMap.put(letter, weights[i]);
reverseMap.put(i, reverseLetter);
}

StringBuilder answer = new StringBuilder();

for(String word : words) {

int sum = 0;

for(char ch : word.toCharArray()) {
sum += weightMap.get(ch);
}

answer.append(reverseMap.get(sum % 26));
}

return answer.toString();
}
}

Approach 2: Optimized Array Solution

Observation

The English alphabet contains only 26 letters.

Instead of using HashMaps:

weightMap.get(ch)

we can directly access:

weights[ch - 'a']

This eliminates hashing overhead entirely.

Why Is This Better?

HashMap operations are O(1) on average, but they still involve:

  1. Hash computation
  2. Bucket lookup
  3. Internal object handling

Array indexing is faster because it directly accesses memory.

Optimized Java Solution

class Solution {

public String mapWordWeights(String[] words, int[] weights) {

StringBuilder answer = new StringBuilder();

for(String word : words) {

int sum = 0;

for(char ch : word.toCharArray()) {
sum += weights[ch - 'a'];
}

int mod = sum % 26;

answer.append((char)('z' - mod));
}

return answer.toString();
}
}

Dry Run

Input

words = ["abcd"]

Assume:

a = 7
b = 5
c = 3
d = 4

Calculate Weight

7 + 5 + 3 + 4 = 19

Apply Modulo

19 % 26 = 19

Reverse Mapping

0 → z
1 → y
2 → x
...
19 → g

Result:

"g"

Complexity Analysis

HashMap Solution

Time Complexity

O(T)

where T is the total number of characters across all words.

Space Complexity

O(1)

Only fixed-size maps of 26 elements are stored.

Optimized Array Solution

Time Complexity

O(T)

Space Complexity

O(1)

No additional data structures are required.

Which Solution Should You Use?

ApproachTimeSpaceInterview Preference
HashMapO(T)O(1)Good
Direct ArrayO(T)O(1)Best

Both solutions are efficient.

However, the array-based approach is typically preferred in coding interviews because:

  1. Simpler implementation
  2. Faster execution
  3. Lower memory overhead
  4. No unnecessary hashing

Interview Discussion

A common follow-up question is:

Can we eliminate both HashMaps?

Yes.

Since:

'a' to 'z'

are contiguous ASCII characters, we can directly compute:

weights[ch - 'a']

Similarly:

(char)('z' - mod)

can generate the reverse mapping without storing another lookup table.

This reduces code complexity while maintaining the same asymptotic performance.

Key Takeaways

  1. Fixed-size alphabets often allow array-based optimizations.
  2. HashMaps improve readability but may not always be necessary.
  3. Modular arithmetic is useful for reducing values into a bounded range.
  4. Character arithmetic can replace lookup tables in many string problems.
  5. Always look for opportunities to replace generic data structures with direct indexing when the input domain is small and fixed.

Conclusion

LeetCode 3838: Weighted Word Mapping is an excellent beginner-friendly problem that demonstrates the practical use of hashing, modular arithmetic, and character manipulation.

While a HashMap-based solution is intuitive and easy to understand, recognizing that the alphabet size is fixed allows us to develop a cleaner and more optimized array-based solution.

Understanding both approaches not only helps solve this problem efficiently but also strengthens the problem-solving mindset needed for technical interviews and competitive programming.

Ai Assistant Kas