Watch 6 video solutions for Mirror Distance of an Integer, a easy level problem involving Math. This walkthrough by ADevOpsBeginner has 112 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
You are given an integer n.
Define its mirror distance as: abs(n - reverse(n)) where reverse(n) is the integer formed by reversing the digits of n.
Return an integer denoting the mirror distance of n.
abs(x) denotes the absolute value of x.
Example 1:
Input: n = 25
Output: 27
Explanation:
reverse(25) = 52.abs(25 - 52) = 27.Example 2:
Input: n = 10
Output: 9
Explanation:
reverse(10) = 01 which is 1.abs(10 - 1) = 9.Example 3:
Input: n = 7
Output: 0
Explanation:
reverse(7) = 7.abs(7 - 7) = 0.
Constraints:
1 <= n <= 109Problem Overview: You are given an integer n. Create its mirror by reversing the decimal digits, then return the absolute difference between the original number and this mirrored value. The task is essentially digit manipulation: construct the reversed integer and compute |n - mirror(n)|.
Approach 1: String-Based Simulation (O(d) time, O(d) space)
Convert the integer to a string and reverse the character sequence. Parse the reversed string back into an integer to obtain the mirrored value. The mirror distance is simply abs(n - mirrored). This approach is straightforward and easy to implement because built-in string operations handle the reversal. Time complexity is O(d) where d is the number of digits, and space complexity is also O(d) due to the temporary string representation.
Approach 2: Mathematical Digit Reversal (O(d) time, O(1) space)
A more space-efficient method reverses the digits using arithmetic. Repeatedly extract the last digit with n % 10, append it to the mirrored number using mirror = mirror * 10 + digit, and remove the digit from the original value with integer division. Once all digits are processed, compute the distance using abs(original - mirror). This approach performs a simple digit-by-digit simulation and avoids extra memory, making the space complexity O(1) while maintaining O(d) time.
Both implementations rely on basic digit manipulation, a common pattern in math and simulation problems. Understanding how to extract and rebuild digits using modulo and division is useful for many related problems involving number reversal or palindromes.
Recommended for interviews: The mathematical digit-reversal approach is usually preferred. Interviewers expect you to handle integer digit operations without converting to strings. Showing the string-based version first demonstrates clarity, but implementing the O(1) space arithmetic solution shows stronger command of math fundamentals and low-level number manipulation.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String-Based Reversal | O(d) | O(d) | Quick implementation when clarity matters more than memory |
| Mathematical Digit Reversal | O(d) | O(1) | Preferred in interviews or memory-constrained environments |