Check if Word Equals Summation of Two Words
EasyPrompt
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).
The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.
- For example, if
s = "acb", we concatenate each letter's letter value, resulting in"021". After converting it, we get21.
You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.
Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
Example 1:
Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
Output: true
Explanation:
The numerical value of firstWord is "acb" -> "021" -> 21.
The numerical value of secondWord is "cba" -> "210" -> 210.
The numerical value of targetWord is "cdb" -> "231" -> 231.
We return true because 21 + 210 == 231.Example 2:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
Output: false
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aab" -> "001" -> 1.
We return false because 0 + 0 != 1.Example 3:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
Output: true
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aaaa" -> "0000" -> 0.
We return true because 0 + 0 == 0.
Constraints:
1 <= firstWord.length,secondWord.length,targetWord.length <= 8firstWord,secondWord, andtargetWordconsist of lowercase English letters from'a'to'j'inclusive.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach directly translates the problem description into code. It involves creating a helper function that first builds a string representation of the numerical value for each word by concatenating the letter values. Then, it parses this string to get the final integer. This method is straightforward and easy to understand but is not the most efficient in terms of space or speed.
Algorithm
- Create a helper function
getNumericalValue(String word)to convert a word to its integer representation. - Inside the helper function, initialize a
StringBuilder. - Iterate through each character
cof the inputword. - For each character, calculate its letter value by subtracting the ASCII value of 'a' (i.e.,
c - 'a'). - Append this integer value to the
StringBuilder. - After the loop, convert the
StringBuilderto aString. - Use
Integer.parseInt()to parse the string into an integer and return it. - In the main function, call this helper function for
firstWord,secondWord, andtargetWordto get their respective numerical values. - Finally, check if the sum of the numerical values of
firstWordandsecondWordis equal to the numerical value oftargetWordand return the boolean result.
Walkthrough
The core idea is to simulate the process described in the problem statement step-by-step. We define a helper method that takes a string as input. This method iterates through the string's characters, converts each character to its corresponding digit ('a' -> 0, 'b' -> 1, etc.), and appends this digit to a StringBuilder. For example, for the word "acb", the StringBuilder would become "021". Once the entire word is processed, the StringBuilder is converted to a String, which is then parsed into an integer using Integer.parseInt(). This process is repeated for all three input words (firstWord, secondWord, targetWord). The main function then simply adds the numerical values of the first two words and compares the sum with the numerical value of the target word.
class Solution { public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { int firstValue = getNumericalValue(firstWord); int secondValue = getNumericalValue(secondWord); int targetValue = getNumericalValue(targetWord); return (firstValue + secondValue) == targetValue; } private int getNumericalValue(String word) { StringBuilder numericString = new StringBuilder(); for (char c : word.toCharArray()) { numericString.append(c - 'a'); } return Integer.parseInt(numericString.toString()); }}Complexity
Time
O(N + M + K). For each word of length L, we iterate through it once to build the string (O(L)) and then parse it (which also takes O(L) time). The total time is the sum of the times for each of the three words.
Space
O(N + M + K), where N, M, and K are the lengths of `firstWord`, `secondWord`, and `targetWord` respectively. This is because we create `StringBuilder` objects whose sizes are proportional to the lengths of the input words.
Trade-offs
Pros
The logic is very intuitive as it directly follows the problem's definition.
The code is easy to write and understand for developers of all levels.
Cons
This approach is less efficient in terms of memory usage because it creates intermediate
StringBuilderandStringobjects for each word.The process of string building and parsing can be slower than direct arithmetic operations, especially for longer strings (though not a major issue with the given constraints).
A more efficient approach is to calculate the numerical value of each word directly using arithmetic, avoiding the creation of intermediate strings. This method treats the conversion process as building a number in base 10. By iterating through the word's characters, we can construct the integer value mathematically, which is significantly better in terms of memory usage and often faster.
Algorithm
- Create a helper function
getNumericalValue(String word). - Inside the helper function, initialize an integer variable, say
total, to 0. - Iterate through each character
cof the inputword. - For each character, calculate its letter value:
digit = c - 'a'. - Update the
totalby treating it as a base-10 number:total = total * 10 + digit. - After iterating through all characters, return the final
total. - In the main function, call this helper for all three words.
- Return the result of comparing the sum of the first two numerical values with the third.
Walkthrough
This optimized method calculates the numerical value without any string manipulation. The logic relies on the way we form numbers. For instance, to form the number 231, we start with 2, then multiply by 10 and add 3 to get 23, then multiply by 10 and add 1 to get 231. We can apply the same principle here. We create a helper function that initializes a result variable to 0. It then iterates through the characters of the word. In each step, it multiplies the current result by 10 and adds the letter value of the current character. This efficiently computes the numerical value in a single pass with constant extra space.
For example, with "acb":
total = 0- Character 'a' (value 0):
total = (0 * 10) + 0 = 0 - Character 'c' (value 2):
total = (0 * 10) + 2 = 2 - Character 'b' (value 1):
total = (2 * 10) + 1 = 21
This avoids the overhead of StringBuilder, String creation, and Integer.parseInt().
class Solution { public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { return getNumericalValue(firstWord) + getNumericalValue(secondWord) == getNumericalValue(targetWord); } private int getNumericalValue(String word) { int total = 0; for (char c : word.toCharArray()) { total = total * 10 + (c - 'a'); } return total; }}Complexity
Time
O(N + M + K), where N, M, and K are the lengths of the three words. We perform a single pass over each word, and the operations within the loop are constant time.
Space
O(1). This approach only uses a few integer variables for calculations, regardless of the input size. No additional space that scales with the input length is required.
Trade-offs
Pros
Extremely space-efficient, using only a constant amount of extra space.
Generally faster due to using simple arithmetic operations instead of more complex string manipulations and parsing.
The code is clean, concise, and elegant.
Cons
The mathematical logic might be slightly less intuitive for a beginner compared to the direct string concatenation method.
Solutions
Solution
class Solution {public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { return f(firstWord) + f(secondWord) == f(targetWord); }private int f(String s) { int res = 0; for (char c : s.toCharArray()) { res = res * 10 + (c - 'a'); } return res; }}/** * @param {string} firstWord * @param {string} secondWord * @param {string} targetWord * @return {boolean} */ var isSumEqual = function (firstWord, secondWord, targetWord) { function f(s) { let res = 0; for (let c of s) { res = res * 10 + (c.charCodeAt() - " a ".charCodeAt()); } return res; } return f(firstWord) + f(secondWord) == f(targetWord); };class Solution {public: bool isSumEqual(string firstWord, string secondWord, string targetWord) { return f(firstWord) + f(secondWord) == f(targetWord); } int f(string s) { int res = 0; for (char c : s) res = res * 10 + (c - 'a'); return res; }};class Solution: def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: def f(s): res = 0 for c in s: res = res * 10 + (ord(c) - ord('a')) return res return f(firstWord) + f(secondWord) == f(targetWord)Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.