Similar Problems
Similar Problems not available
Check If Word Equals Summation Of Two Words - Leetcode Solution
Companies:
LeetCode: Check If Word Equals Summation Of Two Words Leetcode Solution
Difficulty: Easy
Topics: string
Problem Statement:
Given three strings firstWord, secondWord, and targetWord, return true if targetWord is equal to the summation of firstWord and secondWord, or false otherwise.
To summarize, we are given three words - firstWord, secondWord, and targetWord. We have to check if the sum of firstWord and secondWord equals targetWord.
Example:
Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb" Output: true Explanation: The sum of "acb" and "cba" is "cdb", which is equal to the targetWord.
Input: firstWord = "aaa", secondWord = "a", targetWord = "abc" Output: false Explanation: The sum of "aaa" and "a" is "aaaa", which is not equal to the targetWord.
Solution:
The problem simply asks us to add two numbers in string form and compare it with another string. We can solve the problem by following these steps:
-
Convert the given words into a numeric value by assigning unique digits (0-9) to each letter and concatenating the corresponding digits. For instance, if the first character of firstWord is "a", we can assign it the digit 0, second character the digit 1, and so on. By doing this, we can convert a word into its corresponding numeric value. We can accomplish this task by using a hashmap.
-
Once we have converted all three words into their numeric representation, we can simply add the numeric values of firstWord and secondWord and compare the resulting sum with the numeric value of targetWord.
Let's write the code to solve the problem:
class Solution { public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { Map<Character, Integer> map = new HashMap<>();
// Assign digits to each character
for (char c = 'a'; c <= 'j'; c++) {
map.put(c, c - 'a');
}
// Convert the words to their numeric representation
int firstNum = toNumber(firstWord, map);
int secondNum = toNumber(secondWord, map);
int targetNum = toNumber(targetWord, map);
// Check if the sum of first and second word is equal to target word
return (firstNum + secondNum) == targetNum;
}
// Helper method to convert a word to its numeric value
private int toNumber(String word, Map<Character, Integer> map) {
int num = 0;
for (int i = 0; i < word.length(); i++) {
num = num * 10 + map.get(word.charAt(i));
}
return num;
}
}
Time Complexity:
The time complexity of the solution is O(n), where n is the maximum length of the three input strings.
Space Complexity:
The space complexity of the solution is O(1), as the hashmap used to assign digits to characters has only 10 entries.
Check If Word Equals Summation Of Two Words Solution Code
1