Check if Word Equals Summation of Two Words solution and explanation
9 more videos on this problem
Check if Word Equals Summation of Two Words 🔥 | Leetcode 1880 | Contest-243Ayushi Sharma · 6:31 · 921 views
1880. Check if Word Equals Summation of Two Words | LeetCode Weekly Contest | Coders CampCoders Camp · 3:33 · 588 views
1880. Check if Word Equals Summation of Two Words (Leetcode Easy)Programming Live with Larry · 3:12 · 573 views
1880. Check if Word Equals Summation of Two Words | String Easy Leetcode | javaAnushka Bhagchandani · 7:00 · 268 views
1880 check if word equals summation of two words leetcode problem in c++ | leetcode for beginnersCoding enthusiast · 7:28 · 192 views
Leetcode Solution - 1880 Check if Word Equals Summation of Two WordsJohn Leonardo · 5:07 · 139 views
Solving LeetCode problem 1880 in APL (Check if Word Equals Summation of Two Words)Rodrigo's APL Corner · 4:54 · 114 views
LeetCode Weekly Contest 243 Question 1: Check if Word Equals Summation of Two WordsCoding Ninjas Webinars and Contest Editorials · 5:44 · 108 views
Day 192 - Teaching Kids Programming - Check if Word Equals Summation of Two WordsDoctor Lai · 10:16 · 45 views
1880. Check if Word Equals Summation of Two Words - Javascript - Time: O(n) Space: O(1) - LeetcodeAaron Sadino Coding · 11:59 · 13 views
The problem
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).
The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.
- For example, if
s = "acb", we concatenate each letter's letter value, resulting in"021". After converting it, we get21.
You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.
Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
Example 1:
Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb" Output: true Explanation: The numerical value of firstWord is "acb" -> "021" -> 21. The numerical value of secondWord is "cba" -> "210" -> 210. The numerical value of targetWord is "cdb" -> "231" -> 231. We return true because 21 + 210 == 231.
Example 2:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aab" Output: false Explanation: The numerical value of firstWord is "aaa" -> "000" -> 0. The numerical value of secondWord is "a" -> "0" -> 0. The numerical value of targetWord is "aab" -> "001" -> 1. We return false because 0 + 0 != 1.
Example 3:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa" Output: true Explanation: The numerical value of firstWord is "aaa" -> "000" -> 0. The numerical value of secondWord is "a" -> "0" -> 0. The numerical value of targetWord is "aaaa" -> "0000" -> 0. We return true because 0 + 0 == 0.
Constraints:
1 <= firstWord.length,secondWord.length,targetWord.length <= 8firstWord,secondWord, andtargetWordconsist of lowercase English letters from'a'to'j'inclusive.
Approach overview
Problem Overview: Each lowercase character from 'a' to 'j' represents a digit from 0 to 9. Converting a word means replacing every character with its corresponding digit and interpreting the resulting string as a number. The task is to check whether the numeric value of firstWord plus secondWord equals the numeric value of targetWord.
Approach 1: Brute Force Conversion and Comparison (O(n) time, O(n) space)
The direct approach converts each word into its numeric representation using a mapping from characters to digits. Iterate through every character, compute digit = c - 'a', append that digit to a string (or buffer), and then convert the resulting string into an integer using a standard parsing function. After computing values for firstWord, secondWord, and targetWord, compare whether the first two sum to the third. This method is straightforward and mirrors the problem statement exactly. The extra space comes from building intermediate digit strings before parsing. Time complexity is O(n), where n is the total length of all words.
Approach 2: Mapping and Direct Calculation (O(n) time, O(1) space)
You can avoid intermediate strings by constructing the numeric value directly during traversal. Start with value = 0, then iterate through each character and update value = value * 10 + (c - 'a'). This simulates digit concatenation mathematically. Apply the same logic to all three words and check whether value(firstWord) + value(secondWord) == value(targetWord). This eliminates parsing overhead and reduces memory usage since only integers are stored. The time complexity remains O(n) because each character is processed once, but the space complexity drops to O(1).
This problem mainly tests basic manipulation of string characters and simple digit construction, which is common in simulation problems. The numeric construction step also mirrors patterns seen in math-based string conversions where characters represent digits.
Recommended for interviews: The mapping and direct calculation approach. It demonstrates that you understand how digit concatenation works without relying on string parsing utilities. The brute force version shows correct interpretation of the problem, but the constant-space calculation is cleaner and typically what interviewers expect for simple conversion tasks.
Approach 1: Brute Force Conversion and Comparison
This approach directly translates each character of the input strings into its respective letter value, concatenates them to form a number (as a string), and then converts it into an integer. We do this separately for firstWord, secondWord, and targetWord, and finally compare the sum of the first two with the third.
def get_numerical_value(word):
return int(''.join(str(ord(c) - ord('a')) for c in word))
def is_sum_equal(first_word, second_word, target_word):
num_first = get_numerical_value(first_word)
num_second = get_numerical_value(second_word)
num_target = get_numerical_value(target_word)
return num_first + num_second == num_target
if __name__ == "__main__":
print(is_sum_equal('acb', 'cba', 'cdb')) # Output: Truepublic class WordSummation {
public static int getNumericalValue(String word) {
int value = 0;
for (char c : word.toCharArray()) {
value = value * 10 + (c - 'a');
}
return value;
}
public static boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
int numFirst = getNumericalValue(firstWord);
int numSecond = getNumericalValue(secondWord);
int numTarget = getNumericalValue(targetWord);
return numFirst + numSecond == numTarget;
}
public static void main(String[] args) {
System.out.println(isSumEqual("acb", "cba", "cdb")); // prints true
}
}#include <iostream>
#include <string>
int getNumericalValue(const std::string& word) {
int value = 0;
for (char c : word) {
value = value * 10 + (c - 'a');
}
return value;
}
bool isSumEqual(const std::string& firstWord, const std::string& secondWord, const std::string& targetWord) {
int numFirst = getNumericalValue(firstWord);
int numSecond = getNumericalValue(secondWord);
int numTarget = getNumericalValue(targetWord);
return numFirst + numSecond == numTarget;
}
int main() {
std::cout << std::boolalpha << isSumEqual("acb", "cba", "cdb") << std::endl; // should output true
return 0;
}function getNumericalValue(word) {
let value = 0;
for (let char of word) {
value = value * 10 + (char.charCodeAt(0) - 'a'.charCodeAt(0));
}
return value;
}
function isSumEqual(firstWord, secondWord, targetWord) {
let numFirst = getNumericalValue(firstWord);
let numSecond = getNumericalValue(secondWord);
let numTarget = getNumericalValue(targetWord);
return numFirst + numSecond === numTarget;
}
console.log(isSumEqual('acb', 'cba', 'cdb')); // Output: true#include <stdio.h>
#include <string.h>
int getNumericalValue(char* word) {
int value = 0;
while (*word) {
value = value * 10 + (*word - 'a');
word++;
}
return value;
}
int isSumEqual(char* firstWord, char* secondWord, char* targetWord) {
int numFirst = getNumericalValue(firstWord);
int numSecond = getNumericalValue(secondWord);
int numTarget = getNumericalValue(targetWord);
return numFirst + numSecond == numTarget;
}
int main() {
printf("%d\n", isSumEqual("acb", "cba", "cdb")); // should print 1 for true
return 0;
}using System;
public class WordSummation {
public static int GetNumericalValue(string word) {
int value = 0;
foreach (char c in word) {
value = value * 10 + (c - 'a');
}
return value;
}
public static bool IsSumEqual(string firstWord, string secondWord, string targetWord) {
int numFirst = GetNumericalValue(firstWord);
int numSecond = GetNumericalValue(secondWord);
int numTarget = GetNumericalValue(targetWord);
return numFirst + numSecond == numTarget;
}
public static void Main(string[] args) {
Console.WriteLine(IsSumEqual("acb", "cba", "cdb")); // Output: True
}
}Uses a get_numerical_value function that constructs the numerical value of a word using list comprehension and conversion. The equality condition is checked directly using the computed values.
Time Complexity: O(n + m + p), where n, m, and p are the lengths of the given strings. Space Complexity: O(n + m + p), primarily due to the creation of intermediate strings during list comprehension.
Approach 2: Mapping and Direct Calculation
This approach uses a mapping of characters to their numerical equivalents directly and computes the numerical values using mathematical transformations. This avoids concatenating strings and directly supports arithmetic operations on numerical values.
def compute_numerical_value(word):
return sum((ord(c) - ord('a')) * (10 ** i) for i, c in enumerate(reversed(word)))
def is_sum_equal(first_word, second_word, target_word):
return compute_numerical_value(first_word) + compute_numerical_value(second_word) == compute_numerical_value(target_word)
if __name__ == "__main__":
print(is_sum_equal('acb', 'cba', 'cdb')) # Output: Truepublic class WordSummationEfficient {
public static int computeNumericalValue(String word) {
int result = 0;
for (char c : word.toCharArray()) {
result = result * 10 + (c - 'a');
}
return result;
}
public static boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
return computeNumericalValue(firstWord) + computeNumericalValue(secondWord) == computeNumericalValue(targetWord);
}
public static void main(String[] args) {
System.out.println(isSumEqual("acb", "cba", "cdb")); // true
}
}#include <iostream>
#include <string>
int computeNumericalValue(const std::string& word) {
int result = 0, factor = 1;
for (int i = word.size() - 1; i >= 0; --i) {
result += (word[i] - 'a') * factor;
factor *= 10;
}
return result;
}
bool isSumEqual(const std::string& firstWord, const std::string& secondWord, const std::string& targetWord) {
return computeNumericalValue(firstWord) + computeNumericalValue(secondWord) == computeNumericalValue(targetWord);
}
int main() {
std::cout << std::boolalpha << isSumEqual("acb", "cba", "cdb") << std::endl;
return 0;
}function computeNumericalValue(word) {
let result = 0, factor = 1;
for (let i = word.length - 1; i >= 0; i--) {
result += (word.charCodeAt(i) - 'a'.charCodeAt(0)) * factor;
factor *= 10;
}
return result;
}
function isSumEqual(firstWord, secondWord, targetWord) {
return computeNumericalValue(firstWord) + computeNumericalValue(secondWord) === computeNumericalValue(targetWord);
}
console.log(isSumEqual('acb', 'cba', 'cdb')); // Output: true#include <stdio.h>
#include <string.h>
int computeNumericalValue(char* word) {
int result = 0, factor = 1;
for (int i = strlen(word) - 1; i >= 0; i--) {
result += (word[i] - 'a') * factor;
factor *= 10;
}
return result;
}
int isSumEqual(char* firstWord, char* secondWord, char* targetWord) {
int numFirst = computeNumericalValue(firstWord);
int numSecond = computeNumericalValue(secondWord);
int numTarget = computeNumericalValue(targetWord);
return numFirst + numSecond == numTarget;
}
int main() {
printf("%d\n", isSumEqual("acb", "cba", "cdb"));
return 0;
}using System;
public class EfficientWordSummation {
public static int ComputeNumericalValue(string word) {
int result = 0, factor = 1;
for (int i = word.Length - 1; i >= 0; i--) {
result += (word[i] - 'a') * factor;
factor *= 10;
}
return result;
}
public static bool IsSumEqual(string firstWord, string secondWord, string targetWord) {
return ComputeNumericalValue(firstWord) + ComputeNumericalValue(secondWord) == ComputeNumericalValue(targetWord);
}
public static void Main(string[] args) {
Console.WriteLine(IsSumEqual("acb", "cba", "cdb")); // Output: True
}
}The conversion uses direct integer arithmetic by positioning each character's value according to its index power, finalizing with a sum for the correct numerical total.
Time Complexity: O(n + m + p). Space Complexity: O(1), maintaining compact operations.
Approach 3: String to Number
We define a function f(s) to calculate the numerical value of the string s. For each character c in the string s, we convert it to the corresponding number x, then concatenate x sequentially, and finally convert it to an integer.
Finally, we just need to check whether f(firstWord) + f(secondWord) equals f(targetWord).
The time complexity is O(L), where L is the sum of the lengths of all strings in the problem. The space complexity is O(1).
function isSumEqual(firstWord: string, secondWord: string, targetWord: string): boolean {
const f = (s: string): number => {
let ans = 0;
for (const c of s) {
ans = ans * 10 + c.charCodeAt(0) - 97;
}
return ans;
};
return f(firstWord) + f(secondWord) == f(targetWord);
}func isSumEqual(firstWord string, secondWord string, targetWord string) bool {
f := func(s string) (ans int) {
for _, c := range s {
ans = ans*10 + int(c-'a')
}
return
}
return f(firstWord)+f(secondWord) == f(targetWord)
}impl Solution {
pub fn is_sum_equal(first_word: String, second_word: String, target_word: String) -> bool {
fn f(s: &str) -> i64 {
let mut ans = 0;
let a = 'a' as i64;
for c in s.chars() {
let x = c as i64 - a;
ans = ans * 10 + x;
}
ans
}
f(&first_word) + f(&second_word) == f(&target_word)
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Brute Force Conversion and Comparison | Time Complexity: O(n + m + p), where n, m, and p are the lengths of the given strings. Space Complexity: O(n + m + p), primarily due to the creation of intermediate strings during list comprehension. |
| Mapping and Direct Calculation | Time Complexity: O(n + m + p). Space Complexity: O(1), maintaining compact operations. |
| String to Number | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Conversion and Comparison | O(n) | O(n) | When clarity is preferred and using built-in string-to-integer conversion is acceptable |
| Mapping and Direct Calculation | O(n) | O(1) | Best for interviews and optimized solutions with no intermediate strings |
Frequently asked questions
Is Check if Word Equals Summation of Two Words easy or hard?
Check if Word Equals Summation of Two Words is classified as an Easy problem on LeetCode with a high acceptance rate around 75%. It mainly tests understanding of character-to-digit mapping and basic string iteration.
Check if Word Equals Summation of Two Words Python/Java solution
In Python or Java, iterate through the characters of each word and compute value = value * 10 + (ord(c) - ord('a')) or (c - 'a'). Repeat for the three words and compare the resulting integers. The logic is identical across Python, Java, C++, and JavaScript.
How to solve Check if Word Equals Summation of Two Words in O(n)?
Traverse each word and build its numeric value using digit mapping from 'a'–'j' to 0–9. Update the number with value = value * 10 + (c - 'a') for every character. After computing the values for firstWord, secondWord, and targetWord, return whether the first two values sum to the third.
What is the best approach for Check if Word Equals Summation of Two Words?
The best approach is mapping characters to digits and constructing the number directly during iteration. For each character, compute digit = c - 'a' and update value = value * 10 + digit. Convert all three words this way and compare the sum. This runs in O(n) time with O(1) extra space.
Is Check if Word Equals Summation of Two Words asked at Google/Amazon/Meta?
Problems of this type appear in screening rounds at companies like Amazon and Google because they test string manipulation and numeric construction from characters. The difficulty is Easy, but interviewers expect a clean O(n) implementation without unnecessary conversions.
What data structure is used in Check if Word Equals Summation of Two Words?
No complex data structure is required. The solution relies mainly on string traversal and simple arithmetic operations. Character-to-digit conversion is done using ASCII arithmetic such as c - 'a'.
What is the time complexity of Check if Word Equals Summation of Two Words?
The time complexity is O(n), where n is the total number of characters across the three words. Each character is processed exactly once to compute its numeric contribution. No nested loops or additional passes are required.
