We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if Word Equals Summation of Two Words

Number: 2010

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given three strings firstWord, secondWord, and targetWord, each consisting only of letters 'a' through 'j', convert each word into a numerical value by mapping each letter to a digit (with 'a' as 0, 'b' as 1, etc.), concatenating these digits, and converting the resulting string into an integer. Return true if the sum of the numerical values of firstWord and secondWord equals the numerical value of targetWord, and false otherwise.


Key Insights

  • Map each letter to its digit using its alphabetical order starting from 0.
  • Build the numerical value of a word by concatenating each digit.
  • Convert the concatenated string to an integer.
  • Compare the sum of the first two word values with the target word value.

Space and Time Complexity

Time Complexity: O(n) where n is the maximum length among the input words (since each character is processed once).
Space Complexity: O(n) needed for constructing the string representation of each numerical value.


Solution

The solution involves defining a helper function to convert a word into its numerical value. This is achieved by subtracting the ASCII value of 'a' from each character to get its digit, concatenating these digits into a string, and then converting this string to an integer. After obtaining the numerical values for firstWord, secondWord, and targetWord, we simply check if the sum of the first two equals the third.


Code Solutions

# Python solution for "Check if Word Equals Summation of Two Words"

def isSumEqual(firstWord, secondWord, targetWord):
    # Helper function to convert a word to its numerical value
    def word_to_num(word):
        # Convert each letter to its corresponding digit and join them into a string
        num_str = ''.join(str(ord(ch) - ord('a')) for ch in word)
        # Convert the resulting string into an integer
        return int(num_str)
    
    # Convert words to their numerical values
    num1 = word_to_num(firstWord)  # Numerical value for firstWord
    num2 = word_to_num(secondWord) # Numerical value for secondWord
    target_num = word_to_num(targetWord)  # Numerical value for targetWord
    
    # Return true if the sum of firstWord and secondWord equals targetWord's value
    return num1 + num2 == target_num

# Example usage:
print(isSumEqual("acb", "cba", "cdb"))  # Expected output: True
← Back to All Questions