#2443

Sum of Number and Its Reverse

Medium
MathEnumerationTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking every number, we can iterate through potential candidates for the reverse sum. This reduces unnecessary calculations and focuses on valid pairs.

⚙️

Algorithm

4 steps
  1. 1Step 1: Loop through all integers from 0 to num/2 (since both numbers must be non-negative).
  2. 2Step 2: For each integer, calculate its reverse.
  3. 3Step 3: Check if the sum of the integer and its reverse equals num. If yes, return true.
  4. 4Step 4: If no such pair is found after the loop, return false.
solution.py9 lines
1# Full working Python code
2
3def isSumOfNumberAndReverse(num):
4    def reverse(n):
5        return int(str(n)[::-1])
6    for i in range(num // 2 + 1):
7        if i + reverse(i) == num:
8            return True
9    return False

Complexity note: The time complexity is O(n) because we only loop through half of the numbers up to num, and reversing a number takes constant time. The space complexity is O(1) since we use a constant amount of space.

  • 1The sum of a number and its reverse can be efficiently checked by limiting the range of candidates.
  • 2Reversing a number can be done easily with string manipulation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.