#3783
Mirror Distance of an Integer
EasyMathString ManipulationMathematical Operations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
This approach directly manipulates the number to reverse its digits without converting to a string, making it more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to store the reversed number.
- 2Step 2: Use a loop to extract digits from n and build the reversed number.
- 3Step 3: Calculate the absolute difference between n and the reversed number.
solution.py7 lines
1def mirror_distance(n):
2 rev = 0
3 temp = n
4 while temp > 0:
5 rev = rev * 10 + temp % 10
6 temp //= 10
7 return abs(n - rev)ℹ
Complexity note: The time complexity is O(log n) because we are processing each digit of the number, and space complexity is O(1) since we are using a fixed amount of extra space.
- 1Reversing digits can be done mathematically without string manipulation.
- 2Absolute difference is always non-negative.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.