1880. Check if Word Equals Summation of Two Words
Problem Description
You need to determine if two words add up to equal a third word, where each word is converted to a number based on letter positions.
Letter Value System:
- Each letter has a value based on its position in the alphabet, starting from 0
'a' → 0
,'b' → 1
,'c' → 2
, and so on
Numerical Value Calculation: To get the numerical value of a word:
- Convert each letter to its letter value
- Concatenate these values as a string
- Convert the concatenated string to an integer
Example:
- For the word
"acb"
:'a' → 0
,'c' → 2
,'b' → 1
- Concatenate:
"021"
- Convert to integer:
21
Task:
Given three strings firstWord
, secondWord
, and targetWord
(all containing only lowercase letters 'a'
through 'j'
), determine if:
numerical_value(firstWord) + numerical_value(secondWord) = numerical_value(targetWord)
Return true
if the equation holds, false
otherwise.
Intuition
The problem is essentially asking us to perform arithmetic on words that have been encoded as numbers. The key insight is that we need to convert each word into its numerical representation before we can check if the addition equation holds.
Think of each word as a special number system where instead of digits 0-9, we use letters with their alphabetical positions. When we see a word like "acb"
, we need to:
- Map each letter to its position value (
a=0
,c=2
,b=1
) - Treat these values as digits placed side by side (
021
) - Convert this to a regular integer (
21
)
Once we have this conversion process figured out, the solution becomes straightforward - convert all three words to their numerical values and check if firstWord + secondWord = targetWord
.
The conversion process itself follows a pattern similar to how we normally convert strings to integers. For each character in the string:
- Get its letter value by subtracting
'a'
from it (since'a'
maps to 0) - Build the final number by multiplying the current result by 10 and adding the new digit
For example, converting "acb"
step by step:
- Start with
ans = 0
- Process
'a'
:ans = 0 * 10 + 0 = 0
- Process
'c'
:ans = 0 * 10 + 2 = 2
- Process
'b'
:ans = 2 * 10 + 1 = 21
This approach naturally handles the concatenation and conversion in one pass through each string.
Solution Approach
The solution implements a helper function f(s)
that converts a string to its numerical value. Here's how the implementation works:
Helper Function f(s)
:
- Initialize
ans = 0
to store the result anda = ord("a")
to get the ASCII value of'a'
- For each character
c
in the string:- Convert the character to its ASCII value using
ord(c)
- Calculate the letter value:
x = c - a
(this gives us 0 for 'a', 1 for 'b', etc.) - Build the number using the formula:
ans = ans * 10 + x
- Convert the character to its ASCII value using
- Return the final numerical value
Main Logic:
The main function simply calls f()
on all three input strings and checks if the equation holds:
return f(firstWord) + f(secondWord) == f(targetWord)
Example Walkthrough:
Let's trace through firstWord = "acb"
, secondWord = "cdb"
, targetWord = "cfd"
:
For firstWord = "acb"
:
'a'
:x = 0
,ans = 0 * 10 + 0 = 0
'c'
:x = 2
,ans = 0 * 10 + 2 = 2
'b'
:x = 1
,ans = 2 * 10 + 1 = 21
For secondWord = "cdb"
:
'c'
:x = 2
,ans = 0 * 10 + 2 = 2
'd'
:x = 3
,ans = 2 * 10 + 3 = 23
'b'
:x = 1
,ans = 23 * 10 + 1 = 231
For targetWord = "cfd"
:
'c'
:x = 2
,ans = 0 * 10 + 2 = 2
'f'
:x = 5
,ans = 2 * 10 + 5 = 25
'd'
:x = 3
,ans = 25 * 10 + 3 = 253
Check: 21 + 231 = 252 ≠ 253
, so return false
The time complexity is O(n)
where n
is the total length of all three strings, and the space complexity is O(1)
.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's work through a simple example where the equation holds true.
Input: firstWord = "aaa"
, secondWord = "a"
, targetWord = "aab"
Step 1: Convert firstWord = "aaa"
to its numerical value
- Start with
ans = 0
- Process
'a'
(1st): letter value = 0,ans = 0 * 10 + 0 = 0
- Process
'a'
(2nd): letter value = 0,ans = 0 * 10 + 0 = 0
- Process
'a'
(3rd): letter value = 0,ans = 0 * 10 + 0 = 0
- Result:
0
Step 2: Convert secondWord = "a"
to its numerical value
- Start with
ans = 0
- Process
'a'
: letter value = 0,ans = 0 * 10 + 0 = 0
- Result:
0
Step 3: Convert targetWord = "aab"
to its numerical value
- Start with
ans = 0
- Process
'a'
(1st): letter value = 0,ans = 0 * 10 + 0 = 0
- Process
'a'
(2nd): letter value = 0,ans = 0 * 10 + 0 = 0
- Process
'b'
: letter value = 1,ans = 0 * 10 + 1 = 1
- Result:
1
Step 4: Check if the equation holds
firstWord + secondWord = 0 + 0 = 0
targetWord = 1
- Since
0 ≠ 1
, returnfalse
Let's try another example where the equation is true:
Input: firstWord = "j"
, secondWord = "j"
, targetWord = "bi"
Converting each word:
"j"
: letter value = 9, result =9
"j"
: letter value = 9, result =9
"bi"
:'b'
: letter value = 1,ans = 0 * 10 + 1 = 1
'i'
: letter value = 8,ans = 1 * 10 + 8 = 18
- Result:
18
Verification: 9 + 9 = 18
, which equals 18
, so return true
Solution Implementation
1class Solution:
2 def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
3 """
4 Check if the numerical value of firstWord + secondWord equals targetWord,
5 where each letter is mapped to its position in the alphabet (a=0, b=1, ..., z=25).
6
7 Args:
8 firstWord: First word to convert to numerical value
9 secondWord: Second word to convert to numerical value
10 targetWord: Target word to compare the sum against
11
12 Returns:
13 True if firstWord + secondWord equals targetWord numerically, False otherwise
14 """
15
16 def word_to_number(word: str) -> int:
17 """
18 Convert a word to its numerical value where each letter represents a digit.
19 'a' = 0, 'b' = 1, ..., 'z' = 25
20 The word is treated as a multi-digit number in base 10.
21
22 Args:
23 word: The word to convert
24
25 Returns:
26 The numerical value of the word
27 """
28 result = 0
29 base_ascii = ord('a') # ASCII value of 'a' as reference point
30
31 # Process each character in the word
32 for char in word:
33 # Convert character to its alphabetical position (0-25)
34 digit_value = ord(char) - base_ascii
35 # Build the number by shifting previous digits left and adding new digit
36 result = result * 10 + digit_value
37
38 return result
39
40 # Check if sum of first two words equals the target word
41 return word_to_number(firstWord) + word_to_number(secondWord) == word_to_number(targetWord)
42
1class Solution {
2 /**
3 * Checks if the numerical value of firstWord plus secondWord equals targetWord.
4 * Each letter is mapped to a digit: 'a' -> 0, 'b' -> 1, ..., 'j' -> 9.
5 * The resulting string of digits is interpreted as a decimal number.
6 *
7 * @param firstWord First word to convert to numerical value
8 * @param secondWord Second word to convert to numerical value
9 * @param targetWord Target word to compare against the sum
10 * @return true if firstWord + secondWord equals targetWord numerically, false otherwise
11 */
12 public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
13 return convertWordToNumber(firstWord) + convertWordToNumber(secondWord) == convertWordToNumber(targetWord);
14 }
15
16 /**
17 * Converts a word to its numerical value based on letter positions.
18 * Each character 'a' through 'j' maps to digits 0 through 9.
19 * The word is treated as a number in base 10.
20 *
21 * @param word The word to convert (contains only lowercase letters a-j)
22 * @return The numerical value of the word
23 */
24 private int convertWordToNumber(String word) {
25 int numericValue = 0;
26
27 // Process each character in the word
28 for (char character : word.toCharArray()) {
29 // Shift existing digits left (multiply by 10) and add new digit
30 // 'a' - 'a' = 0, 'b' - 'a' = 1, etc.
31 numericValue = numericValue * 10 + (character - 'a');
32 }
33
34 return numericValue;
35 }
36}
37
1class Solution {
2public:
3 bool isSumEqual(string firstWord, string secondWord, string targetWord) {
4 // Lambda function to convert a word to its numerical value
5 // Each letter 'a' to 'j' represents digits 0 to 9 respectively
6 auto convertWordToNumber = [](string& word) -> int {
7 int numericalValue = 0;
8
9 // Iterate through each character in the word
10 for (char character : word) {
11 // Convert letter to digit: 'a' -> 0, 'b' -> 1, ..., 'j' -> 9
12 int digit = character - 'a';
13
14 // Build the number by shifting previous digits left and adding new digit
15 numericalValue = numericalValue * 10 + digit;
16 }
17
18 return numericalValue;
19 };
20
21 // Check if the sum of first two words equals the target word
22 return convertWordToNumber(firstWord) + convertWordToNumber(secondWord) == convertWordToNumber(targetWord);
23 }
24};
25
1/**
2 * Checks if the numerical value of firstWord plus secondWord equals targetWord
3 * where each letter represents a digit (a=0, b=1, ..., z=25)
4 * @param firstWord - First word to convert to number
5 * @param secondWord - Second word to convert to number
6 * @param targetWord - Target word to compare the sum against
7 * @returns true if firstWord + secondWord equals targetWord numerically
8 */
9function isSumEqual(firstWord: string, secondWord: string, targetWord: string): boolean {
10 /**
11 * Converts a word to its numerical value
12 * Each character is mapped to a digit: 'a'->0, 'b'->1, ..., 'z'->25
13 * The digits are concatenated to form the final number
14 * @param word - The word to convert
15 * @returns The numerical value of the word
16 */
17 const convertWordToNumber = (word: string): number => {
18 let numericValue = 0;
19
20 // Process each character in the word
21 for (const character of word) {
22 // Shift existing digits left and add new digit
23 // 'a' has ASCII 97, so subtract 97 to get 0-based value
24 numericValue = numericValue * 10 + character.charCodeAt(0) - 97;
25 }
26
27 return numericValue;
28 };
29
30 // Check if sum of first two words equals the target word
31 return convertWordToNumber(firstWord) + convertWordToNumber(secondWord) === convertWordToNumber(targetWord);
32}
33
Time and Space Complexity
The time complexity is O(L)
, where L
is the sum of the lengths of all three strings (firstWord
, secondWord
, and targetWord
). This is because the function f
iterates through each character of a string exactly once, performing constant-time operations for each character. Since f
is called three times (once for each string), and each call processes every character in its respective string, the total time is proportional to the sum of all string lengths.
The space complexity is O(1)
. The algorithm uses only a fixed amount of extra space regardless of input size. The helper function f
maintains only two integer variables (ans
and a
), and the map(ord, s)
operation creates an iterator that doesn't consume additional space proportional to the string length. No auxiliary data structures that scale with input size are created.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Leading Zeros Confusion
A common misconception is thinking that leading zeros might cause issues or need special handling. For example, if a word starts with 'a' (which maps to 0), like "aab" → "001" → 1, developers might worry about the leading zero disappearing.
Why it's not a problem: The algorithm naturally handles this correctly. When we build the number using result = result * 10 + digit_value
, starting with 'a' (0) simply keeps the result at 0 until we encounter a non-'a' character. The mathematical operations handle this automatically without any special cases needed.
2. Integer Overflow Concerns
Since we're potentially creating large numbers from long strings, developers might worry about integer overflow, especially in languages with fixed integer sizes.
Solution: In Python, integers have arbitrary precision, so overflow isn't an issue. However, if implementing in languages like Java or C++, consider:
- Using
long
orlong long
data types - Adding overflow checks if the input strings can be very long
- The problem constraint mentions only letters 'a' through 'j', which limits the maximum digit value to 9, making the resulting numbers standard decimal integers
3. Incorrect ASCII Arithmetic
A subtle but critical error occurs when developers try to directly use character values without proper conversion:
Wrong approach:
def word_to_number(word):
result = ""
for char in word:
result += str(ord(char) - ord('a'))
return int(result)
Why it's inefficient: This creates an intermediate string representation, which is unnecessary and less efficient than building the number directly through arithmetic operations.
4. Misunderstanding the Base System
Some developers might think this is a base-26 number system since there are 26 letters in the alphabet.
Clarification: Despite having 26 possible letter values (0-25), we're still working in base-10. Each letter position contributes its value as a decimal digit. The problem specifically limits input to letters 'a' through 'j' (values 0-9), making it exactly like decimal numbers where each position can only hold digits 0-9.
5. Edge Case: Empty Strings
The code doesn't explicitly handle empty strings, which would return 0 from the helper function.
Consideration: While mathematically correct (empty string → 0), verify whether the problem constraints allow empty strings. If they do, the current implementation handles them correctly. If not, add validation:
if not word: return 0 # or raise an exception based on requirements
Which of the two traversal algorithms (BFS and DFS) can be used to find whether two nodes are connected?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!