LeetCode 2443 - Sum of Number and Its Reverse
Here’s a complete, detailed solution guide for LeetCode 2443 - Sum of Number and Its Reverse, fully following your formatting rules.
Difficulty: 🟡 Medium
Topics: Math, Enumeration
Solution
Here’s a complete, detailed solution guide for LeetCode 2443 - Sum of Number and Its Reverse, fully following your formatting rules.
Problem Understanding
The problem asks whether a given non-negative integer num can be expressed as the sum of a non-negative integer x and its reversed version reverse(x). In other words, we are asked to find whether there exists some integer x >= 0 such that:
x + reverse(x) = num
Here, reverse(x) means reversing the decimal digits of x. For example, if x = 123, then reverse(x) = 321. Note that leading zeros in the reversed number are allowed: reverse(140) = 041 = 41.
The input is constrained to 0 <= num <= 10^5, which is a manageable size for enumeration or digit-based analysis. Edge cases that can challenge naive solutions include small numbers, numbers with trailing zeros, and numbers that cannot be represented in any sum of a number and its reverse.
The expected output is a boolean true if such an x exists, and false otherwise.
Approaches
The brute-force approach is straightforward: try every possible x from 0 to num, reverse it, and check if x + reverse(x) == num. This guarantees correctness because it examines all potential candidates. However, it is inefficient for large num since it could require up to num + 1 iterations.
The key observation for an optimal approach is that the maximum possible x to consider is num itself, but we can often use a more intelligent check by iterating from 0 to num and early exiting when x + reverse(x) exceeds num. Given the constraints, this is fast enough. There is no need for complex number theory or digit DP here because num is bounded by 10^5.
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Brute Force | O(num * d) | O(1) | Try every x from 0 to num and compute reverse(x) where d is digits in x |
| Optimal | O(num * d) | O(1) | Same as brute force but optimized with early exit; simple enumeration is sufficient due to constraints |
Algorithm Walkthrough
- Initialize a loop for
xfrom0tonum. We consider all possible candidates for the number that might form the sum. - For each
x, compute its reversed valuerev_xby convertingxto a string, reversing it, and converting back to an integer. - Check whether the sum
x + rev_xequalsnum. - If a match is found, return
Trueimmediately because we only need one valid solution. - If the loop completes without finding a match, return
False.
Why it works: Every possible non-negative integer less than or equal to num is considered. Since the reverse operation is well-defined, this ensures that if a solution exists, it will be found. Early termination upon the first match guarantees efficiency.
Python Solution
class Solution:
def sumOfNumberAndReverse(self, num: int) -> bool:
for x in range(num + 1):
rev_x = int(str(x)[::-1])
if x + rev_x == num:
return True
return False
The Python implementation iterates from 0 to num. For each candidate x, it converts it to a string, reverses the string, converts back to an integer, and checks the sum. If the sum matches num, it returns True. If no valid x is found after the loop, it returns False.
Go Solution
func sumOfNumberAndReverse(num int) bool {
reverse := func(x int) int {
rev := 0
for x > 0 {
rev = rev*10 + x%10
x /= 10
}
return rev
}
for x := 0; x <= num; x++ {
if x+reverse(x) == num {
return true
}
}
return false
}
In Go, we define a helper function reverse that computes the reverse of an integer without converting to a string. The main loop iterates from 0 to num, and for each x, it checks whether x + reverse(x) == num. If a match is found, it returns true. Otherwise, it returns false at the end. This avoids the overhead of string conversion and is more idiomatic in Go.
Worked Examples
Example 1: num = 443
| x | reverse(x) | x + reverse(x) | Match? |
|---|---|---|---|
| 0 | 0 | 0 | No |
| 1 | 1 | 2 | No |
| ... | ... | ... | ... |
| 172 | 271 | 443 | Yes |
Returns True.
Example 2: num = 63
| x | reverse(x) | x + reverse(x) | Match? |
|---|---|---|---|
| 0 | 0 | 0 | No |
| 1 | 1 | 2 | No |
| 2 | 2 | 4 | No |
| ... | ... | ... | ... |
No x satisfies the condition. Returns False.
Example 3: num = 181
| x | reverse(x) | x + reverse(x) | Match? |
|---|---|---|---|
| 0 | 0 | 0 | No |
| 1 | 1 | 2 | No |
| ... | ... | ... | ... |
| 140 | 41 | 181 | Yes |
Returns True.
Complexity Analysis
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(num * d) | Loop from 0 to num; reversing x takes O(d) where d is number of digits in x |
| Space | O(1) | Only constant extra space is used for the reverse calculation |
Since num <= 10^5 and digits d <= 6, this is efficient enough for all inputs within constraints.
Test Cases
# Provided examples
assert Solution().sumOfNumberAndReverse(443) == True # 172 + 271 = 443
assert Solution().sumOfNumberAndReverse(63) == False # no solution
assert Solution().sumOfNumberAndReverse(181) == True # 140 + 41 = 181
# Edge cases
assert Solution().sumOfNumberAndReverse(0) == True # 0 + 0
assert Solution().sumOfNumberAndReverse(1) == True # 0 + 1
assert Solution().sumOfNumberAndReverse(10) == True # 1 + 1 reversed is 1? No, must check, correct is 1+1=2? Actually 10 = 1+1 reversed? No 10=1+1? False. Correct: 10=1+1? False. Best is 10=1+1 reversed? False. Actually 10=1+1 reversed? No. 10=1+1 reversed=2? No. 10=9+9 reversed=9+9=18? No. Actually 10=5+5 reversed=5+5=10? Yes. So True
assert Solution().sumOfNumberAndReverse(100000) == True # maximum input
# Additional checks
assert Solution().sumOfNumberAndReverse(101) == True # 50 + 50 reversed = 50 + 5? Actually 50 reversed=5, 50+5=55? No. Better: 91 + 19 = 110? No. Actually, 55+55 reversed=55+55=110. Actually 101? 52+25=77? 101? 47+74=121? 101? 56+65=121? 101? 100+1=100+1=101. 100 reversed=1, 100+1=101. Yes, True
| Test | Why |
|---|---|
| 443 | Matches a number with a valid sum of number and reverse |
| 63 | No valid sum exists |
| 181 | Valid sum with leading zero in reversed number |
| 0 | Smallest input, edge case |
| 1 | Smallest positive input, edge case |
| 10 | Edge case where solution exists in middle range |
| 100000 | Maximum input constraint |
| 101 | Solution exists with a reversed number having trailing zeros |
Edge Cases
Zero Input: num = 0 is a valid edge case since 0 + reverse(0) = 0. The implementation handles this because the loop includes x = 0.
Trailing Zeros: Numbers like 100 or 101 are tricky because reversing may drop leading zeros. The Python string reverse handles this naturally. In Go, the mathematical reversal process also handles zeros correctly.
Maximum Input: num = 100000 is the largest allowed input. The algorithm remains efficient because the loop range