#2119

A Number After a Double Reversal

Easy
MathMathString Manipulation
LeetCode ↗

Approaches

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

Intuition

Time O(1)Space O(1)

The optimal solution recognizes that if a number ends with zero (except for zero itself), it cannot equal its double-reversed form. Hence, we can directly check this condition without performing unnecessary reversals.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the number is zero; if yes, return true.
  2. 2Step 2: If the number ends with zero, return false.
  3. 3Step 3: Otherwise, return true since reversing twice will yield the original number.
solution.py2 lines
1def isSameAfterReversals(num):
2    return num == 0 or num % 10 != 0

Complexity note: The time complexity is O(1) because we are only performing a constant number of operations. The space complexity is also O(1) as we are not using any additional data structures.

  • 1Reversing a number can lead to loss of leading zeros, which is crucial for this problem.
  • 2Any number that ends with zero (except zero itself) will not equal its double-reversed form.

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