3783. Mirror Distance of an Integer
Problem Description
You are given an integer n.
We define the mirror distance of n as the absolute difference between n and the integer obtained by reversing its digits. Formally, the mirror distance equals abs(n - reverse(n)), where reverse(n) is the integer formed by reversing the order of the digits of n.
For example, if n = 123, then reverse(n) = 321, and the mirror distance is abs(123 - 321) = 198.
Your task is to compute and return the mirror distance of n.
Here, abs(x) denotes the absolute value of x, which is x if x is non-negative, and -x otherwise.
How We Pick the Algorithm
Why Math / Bit Manipulation?
This problem maps to Math / Bit Manipulation through a short path in the full flowchart.
Computing the absolute difference between a number and its digit-reversed form is a straightforward arithmetic computation.
Open in FlowchartIntuition
The problem directly tells us what to compute: the absolute difference between n and its digit-reversed value. So the core of the task is simply to figure out how to reverse the digits of n.
To reverse an integer, we can think about how its digits are arranged. The last digit of n should become the first digit of the reversed number, the second-to-last digit becomes the second, and so on. There are two natural ways to achieve this:
-
String manipulation: Convert
nto a string, reverse the characters, and convert it back to an integer. This is the most concise approach, since reversing a string is straightforward. -
Mathematical extraction: Repeatedly take the last digit of
nusingn % 10, build up the reversed value by computingy = y * 10 + n % 10, and then drop the last digit withn //= 10. Repeat untilnbecomes0.
Once we have reverse(n), the answer follows immediately by plugging the two values into abs(n - reverse(n)). Since there are no tricky edge cases beyond reversing the digits correctly, the solution is a direct simulation of the definition given in the problem.
Pattern Learn more about Math patterns.
Solution Approach
Solution 1: Simulation
We define a function reverse(x) to reverse the digits of integer x. Specifically, we initialize a variable y to 0, then repeatedly append the last digit of x to the end of y, and remove the last digit from x, until x becomes 0. Finally, y is the reversed integer.
The reversal works as follows:
- Take the last digit of
xwithx % 10. - Update
yby computingy = y * 10 + x % 10. Multiplyingyby10shifts its existing digits left, making room for the new digit at the end. - Remove the last digit of
xwithx //= 10. - Repeat until
xbecomes0.
Next, we compute the mirror distance of integer n, which is abs(n - reverse(n)), and return the result.
In the given Python implementation, we use a more concise string-based approach. We convert n to a string with str(n), reverse it using slicing [::-1], and convert it back to an integer with int(...). This directly produces reverse(n), after which we return abs(n - int(str(n)[::-1])).
The time complexity is O(log n), where n is the given integer, since the number of digits in n is proportional to log n. The space complexity is O(log n) as well, due to the storage needed for the digits during reversal.
Example Walkthrough
Let's trace through the solution using a small example: n = 152.
Goal: Compute the mirror distance, which is abs(n - reverse(n)).
Step 1: Reverse the digits of n using the mathematical extraction method.
We start with x = 152 and y = 0 (where y will accumulate the reversed value).
| Iteration | x (before) | x % 10 (last digit) | y = y * 10 + (x % 10) | x //= 10 (after) |
|---|---|---|---|---|
| 1 | 152 | 2 | 0 * 10 + 2 = 2 | 15 |
| 2 | 15 | 5 | 2 * 10 + 5 = 25 | 1 |
| 3 | 1 | 1 | 25 * 10 + 1 = 251 | 0 |
Once x becomes 0, we stop. The reversed value is y = 251.
Cross-check with the string method:
str(152)is"152", reversing the characters gives"251", andint("251")is251. Both approaches agree.
Step 2: Compute the mirror distance.
abs(n - reverse(n)) = abs(152 - 251) = abs(-99) = 99
Result: The mirror distance of 152 is 99.
Why this works: Notice in Step 1 how each multiplication of y by 10 shifts its existing digits to the left, opening up the ones place for the next digit pulled from the back of x. The digit that was last in n (the 2) ends up first in y, which is exactly what reversal means. After that, plugging both numbers into abs(...) directly follows the problem's definition.
Solution Implementation
1class Solution:
2 def mirrorDistance(self, n: int) -> int:
3 # Convert the number to a string so we can reverse its digits
4 original_str = str(n)
5
6 # Reverse the string representation of the number
7 reversed_str = original_str[::-1]
8
9 # Convert the reversed string back to an integer
10 reversed_number = int(reversed_str)
11
12 # Return the absolute difference between the original number
13 # and its digit-reversed counterpart
14 return abs(n - reversed_number)
151class Solution {
2 /**
3 * Computes the absolute difference between a number and its digit-reversed form.
4 *
5 * @param n the input number
6 * @return the absolute distance between n and reverse(n)
7 */
8 public int mirrorDistance(int n) {
9 return Math.abs(n - reverse(n));
10 }
11
12 /**
13 * Reverses the decimal digits of the given number.
14 *
15 * @param x the number whose digits should be reversed
16 * @return the digit-reversed value of x
17 */
18 private int reverse(int x) {
19 int reversed = 0;
20 // Process each digit from least significant to most significant.
21 for (; x > 0; x /= 10) {
22 // Shift existing digits left and append the current last digit.
23 reversed = reversed * 10 + x % 10;
24 }
25 return reversed;
26 }
27}
281class Solution {
2public:
3 int mirrorDistance(int n) {
4 // Lambda to reverse the digits of an integer.
5 // Example: 123 -> 321
6 auto reverse = [](int x) -> int {
7 int reversed = 0;
8 // Process each digit from the least significant to the most significant.
9 for (; x; x /= 10) {
10 // Append the current last digit (x % 10) to the reversed number.
11 reversed = reversed * 10 + x % 10;
12 }
13 return reversed;
14 };
15
16 // The mirror distance is the absolute difference between
17 // the original number and its digit-reversed counterpart.
18 return std::abs(n - reverse(n));
19 }
20};
211/**
2 * Computes the absolute difference between a number and its digit-reversed value.
3 *
4 * @param n - The input non-negative integer.
5 * @returns The absolute distance between `n` and the number formed by reversing its digits.
6 */
7function mirrorDistance(n: number): number {
8 /**
9 * Reverses the decimal digits of a non-negative integer.
10 *
11 * @param x - The number whose digits should be reversed.
12 * @returns The integer obtained by reversing the digits of `x`.
13 */
14 const reverse = (x: number): number => {
15 // Accumulates the reversed number.
16 let reversed = 0;
17
18 // Strip the last digit on each iteration until no digits remain.
19 for (; x > 0; x = Math.floor(x / 10)) {
20 // Shift the accumulated value left by one decimal place
21 // and append the current last digit of `x`.
22 reversed = reversed * 10 + (x % 10);
23 }
24
25 return reversed;
26 };
27
28 // The mirror distance is the absolute gap between `n` and its reversal.
29 return Math.abs(n - reverse(n));
30}
31Time and Space Complexity
-
Time Complexity:
O(log n). The number of digits innis proportional tolog n. Converting the integer to a string viastr(n)takesO(log n)time, reversing the string with[::-1]takesO(log n)time, and converting the reversed string back to an integer withint(...)also takesO(log n)time. The final subtraction andabsoperation run inO(log n)time as well. Therefore, the overall time complexity isO(log n). -
Space Complexity:
O(log n). The string representation ofnrequiresO(log n)space to store its digits, and the reversed string created by[::-1]also occupiesO(log n)space. Hence, the space complexity isO(log n).
Pattern Learn more about how to find time and space complexity quickly.
Common Pitfalls
Pitfall 1: Mishandling Trailing Zeros During Reversal
The most common mistake is forgetting that trailing zeros disappear when a number is reversed. When n ends in one or more zeros, the reversed number has fewer digits than the original.
For example, if n = 1200:
reverse(n)is not0021but simply21(leading zeros are dropped automatically when converting back to an integer).- The mirror distance is
abs(1200 - 21) = 1179.
Why this is a pitfall: Programmers who try to reverse the number with a fixed-width assumption (e.g., padding to match the original length) will get the wrong answer. The string slicing approach int(str(n)[::-1]) handles this correctly because int("0021") automatically becomes 21. However, if you manually build the reversed number and forget that the leading zeros must be discarded, you may produce an incorrect result.
Solution: Rely on int() conversion to strip leading zeros, or in a manual digit-by-digit approach, the math naturally handles it:
class Solution:
def mirrorDistance(self, n: int) -> int:
x, y = n, 0
while x:
y = y * 10 + x % 10 # Leading zeros never get "added" since y starts at 0
x //= 10
return abs(n - y)
In this loop, trailing zeros of n are consumed at the start (contributing y = 0 * 10 + 0 = 0), so they vanish naturally—matching the behavior of the string approach.
Pitfall 2: Assuming the Input Could Be Negative
The problem states n is an integer, and the example uses positive values. A pitfall is over-engineering for negative inputs without confirming the constraints. If n could be negative (e.g., n = -123), the string str(-123) is "-123", and reversing it yields "321-", which raises a ValueError when passed to int().
Solution: If negative numbers are possible, handle the sign separately:
class Solution:
def mirrorDistance(self, n: int) -> int:
sign = -1 if n < 0 else 1
reversed_number = sign * int(str(abs(n))[::-1])
return abs(n - reversed_number)
Always verify the constraints before adding this complexity—if n is guaranteed non-negative, the simpler version suffices.
Pitfall 3: Confusing Integer and String Operations
A subtle pitfall is forgetting the final conversion back to an integer. Writing str(n)[::-1] alone returns a string, not a number. Attempting arithmetic like abs(n - str(n)[::-1]) will raise a TypeError because you cannot subtract a string from an integer.
Solution: Always wrap the reversed string in int(...) before performing arithmetic:
reversed_number = int(str(n)[::-1]) # Correct: produces an integer
return abs(n - reversed_number)
Ready to land your dream job?
Unlock your dream job with a 5-minute quiz for a personalized study roadmap!
Get My RoadmapWhich of the following shows the order of node visit in a Breadth-first Search?

Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion If you prefer videos here's a video that explains recursion in a fun and easy way Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask him
Want a Structured Path to Master System Design Too? Don’t Miss This!