#1880
Check if Word Equals Summation of Two Words
EasyStringString ManipulationMathematical Operations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of converting the entire string to an integer, we can calculate the numerical values directly while iterating through the characters. This avoids the overhead of string manipulation and conversion.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two sums for firstWord and secondWord.
- 2Step 2: Iterate through each character of both words simultaneously, calculating their respective numerical values.
- 3Step 3: Calculate the numerical value of targetWord in a similar manner.
- 4Step 4: Return true if the sum of the first two equals the value of targetWord.
solution.py9 lines
1# Full working Python code
2
3def is_sum_equal(firstWord, secondWord, targetWord):
4 def calculate_value(word):
5 total = 0
6 for c in word:
7 total = total * 10 + (ord(c) - ord('a'))
8 return total
9 return calculate_value(firstWord) + calculate_value(secondWord) == calculate_value(targetWord)ℹ
Complexity note: The time complexity is O(n) because we are iterating through each character of the words only once to compute their values, which is more efficient than the brute force method.
- 1Understanding how to convert characters to their numerical values is crucial.
- 2Efficiently calculating values without unnecessary conversions can save time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.