algoadvance

LeetCode 1880: Check if Word Equals Summation of Two Words

You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' to 'j' inclusive.

You need to determine if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, where each character represents a digit from 0 to 9, i.e., ‘a’ represents 0, ‘b’ represents 1, and so on until ‘j’ which represents 9.

Clarifying Questions

  1. Are all the input strings guaranteed to be non-empty?
    • Yes, according to the problem statement.
  2. Can the words have different lengths?
    • Yes, the input strings can have different lengths.
  3. Are there any constraints on the length of the strings?
    • The length of each string is between 1 and 8 inclusive.

Strategy

  1. Conversion Logic:
    • Convert each character in the strings to its corresponding numeric value by using its position in the alphabet.
    • Calculate the numerical value of each word by treating these digits as a normal integer.
  2. Comparison:
    • Sum the numerical values of firstWord and secondWord.
    • Compare the sum with the numerical value of targetWord.

Code

Let’s implement this step-by-step.

def isSumEqual(firstWord: str, secondWord: str, targetWord: str) -> bool:
    def word_to_number(word: str) -> int:
        num_str = ''.join(str(ord(char) - ord('a')) for char in word)
        return int(num_str)
    
    # Calculate the numeric representations of the words
    first_num = word_to_number(firstWord)
    second_num = word_to_number(secondWord)
    target_num = word_to_number(targetWord)
    
    # Check if their summation equals the target number
    return (first_num + second_num) == target_num

# Example Usage
firstWord = "acb"
secondWord = "cba"
targetWord = "cdb"
print(isSumEqual(firstWord, secondWord, targetWord))  # Output: True

Time Complexity

Thus, the overall time complexity is O(N), where N is the length of the longest string among the three input words.

Try our interview co-pilot at AlgoAdvance.com