Leetcode 1880: Check if Word Equals Summation of Two Words

grid47
grid47
Exploring patterns and algorithms
May 3, 2024 5 min read

You are given three strings: ‘firstWord’, ‘secondWord’, and ’targetWord’. Each string contains only lowercase English letters from ‘a’ to ‘j’. The value of each letter corresponds to its position in the alphabet starting from ‘a’ as 0 (‘a’ -> 0, ‘b’ -> 1, …, ‘j’ -> 9). The value of a string is the concatenation of the values of its letters, which is then interpreted as an integer. Your task is to check if the sum of the values of ‘firstWord’ and ‘secondWord’ equals the value of ’targetWord’. Return true if it does, and false otherwise.
Problem
Approach
Steps
Complexity
Input: You are given three strings 'firstWord', 'secondWord', and 'targetWord'. Each string consists of lowercase letters from 'a' to 'j'.
Example: firstWord = 'acb', secondWord = 'cba', targetWord = 'cdb'
Constraints:
• 1 <= firstWord.length, secondWord.length, targetWord.length <= 8
• firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.
Output: Return true if the sum of the numerical values of 'firstWord' and 'secondWord' equals the numerical value of 'targetWord'. Otherwise, return false.
Example: true
Constraints:
Goal: Convert each word to its numerical value and check if the sum of the values of 'firstWord' and 'secondWord' equals 'targetWord'.
Steps:
• For each word, convert each character to its corresponding value and concatenate them to form an integer.
• Check if the sum of the first and second word values equals the target word value.
Goal: The given strings consist of lowercase letters from 'a' to 'j'. The lengths of the strings are between 1 and 8.
Steps:
• The length of each string is between 1 and 8.
• Each character in the strings is between 'a' and 'j'.
Assumptions:
• The input strings contain only lowercase English letters from 'a' to 'j'.
• The values of the words are formed by concatenating the positions of the characters in the alphabet.
Input: Example 1: firstWord = 'acb', secondWord = 'cba', targetWord = 'cdb'
Explanation: The numerical value of 'acb' is 21, the value of 'cba' is 210, and the value of 'cdb' is 231. The sum of 21 and 210 equals 231, so the result is true.

Input: Example 2: firstWord = 'aaa', secondWord = 'a', targetWord = 'aab'
Explanation: The numerical value of 'aaa' is 0, the value of 'a' is 0, and the value of 'aab' is 1. The sum of 0 and 0 does not equal 1, so the result is false.

Input: Example 3: firstWord = 'aaa', secondWord = 'a', targetWord = 'aaaa'
Explanation: The numerical value of 'aaa' is 0, the value of 'a' is 0, and the value of 'aaaa' is 0. The sum of 0 and 0 equals 0, so the result is true.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus