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

Difficulty: Easy


Problem Description

You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters from 'a' to 'j'. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord. The numerical value of a string is determined by concatenating the letter values of each letter in the string, where the letter value is its position in the alphabet starting from 0 (i.e., 'a' -> 0, 'b' -> 1, ... 'j' -> 9).


Key Insights

  • The problem requires converting strings into numerical values based on letter positions.
  • The numerical value of a string is obtained by concatenating the positions of each character, then converting the resulting string into an integer.
  • We only need to compare the sum of the numerical values of firstWord and secondWord to the numerical value of targetWord.

Space and Time Complexity

Time Complexity: O(n), where n is the maximum length of the input strings (up to 8).
Space Complexity: O(1), as we use a constant amount of space for calculations.


Solution

The solution involves the following steps:

  1. Create a helper function to convert a given string into its numerical value by:
    • Iterating over each character.
    • Calculating its position by subtracting the ASCII value of 'a' from the ASCII value of the character.
    • Concatenating these positions to form a single numeric string.
    • Converting that string to an integer.
  2. Compute the numerical values for firstWord, secondWord, and targetWord.
  3. Check if the sum of the first two numerical values equals the third.

Code Solutions

def word_to_number(word):
    # Convert each character in the word to its corresponding numerical value
    return int(''.join(str(ord(char) - ord('a')) for char in word))

def is_sum_equal(firstWord, secondWord, targetWord):
    # Calculate numerical values
    first_num = word_to_number(firstWord)
    second_num = word_to_number(secondWord)
    target_num = word_to_number(targetWord)
    
    # Check if the sum equals the target
    return first_num + second_num == target_num
← Back to All Questions