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.
firstWord
and secondWord
.targetWord
.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
Thus, the overall time complexity is O(N), where N is the length of the longest string among the three input words.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?