Check if word equals summation of two words

May 19, 2023

array-and-hashmap

Problem URL: Check if word equals summation of two words

We can convert the words to integers and check if the sum of the first two integers equals the third integer.

class Solution:
    def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
        def convert(word: str) -> int:
            res = 0
            for c in word:
                res = res * 10 + ord(c) - ord('a')
            return res

        return convert(firstWord) + convert(secondWord) == convert(targetWord)

Time complexity: O(n) where n is the length of the longest word. Space complexity: O(1)

We can also achieve the same result without converting the words to integers.

class Solution:
    def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:
        firstnumval = ''
        for i in firstWord: 
            firstnumval += str(ord(i) - 97)

        secondnumval = '' 
        for i in secondWord: 
            secondnumval += str(ord(i) - 97)

        targetnumval = ''
        for i in targetWord: 
            targetnumval += str(ord(i) - 97)

        return int(firstnumval) + int(secondnumval) == int(targetnumval)

Time complexity: O(n) where n is the length of the longest word.
Space complexity: O(1)