3783. Mirror Distance of an Integer
Problem Statement
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.
Thus, the answer is abs(25 - 52) = 27.
Example 2
Input: n = 10
Output: 9
Explanation:
reverse(10) = 01 which is 1.
Thus, the answer is abs(10 - 1) = 9.
Example 3
Input: n = 7
Output: 0
Explanation:
reverse(7) = 7.
Thus, the answer is abs(7 - 7) = 0.
Key Insight
The solution requires understanding these crucial observations:
- We need to reverse the digits of the integer
n - The reversal should ignore leading zeros in the result (e.g., reverse(10) = 1, not 01)
- We need to compute the absolute difference between the original and reversed numbers
- For single-digit numbers or palindromic numbers, the mirror distance will be 0
- The mathematical approach using modulo/division is efficient and avoids string conversion overhead
Alternative approach: Convert to string, reverse the string, convert back to integer.
Approach 1: Mathematical Reversal (Optimal)
Reverse the integer mathematically using modulo and division operations. This approach is efficient and avoids string conversion overhead.
Algorithm Steps
- Initialize
reversed = 0and create a copytemp = n - While
temp > 0:- Extract last digit:
digit = temp % 10 - Append to reversed:
reversed = reversed * 10 + digit - Remove last digit:
temp = temp / 10
- Extract last digit:
- Compute
abs(n - reversed) - Return the result
How It Works
This approach builds the reversed number digit by digit. For example, for n = 123:
- Iteration 1: digit = 3, reversed = 3, temp = 12
- Iteration 2: digit = 2, reversed = 32, temp = 1
- Iteration 3: digit = 1, reversed = 321, temp = 0
Complexity Analysis
| Time Complexity | Space Complexity |
|---|---|
| O(d) | O(1) |
Where d is the number of digits in n. We process each digit once with constant extra space.
class Solution {
public:
int mirrorDistance(int n) {
int temp = 0;
int num = n;
while (num) {
int digit = num % 10;
temp = temp * 10 + digit;
num /= 10;
}
return abs(n - temp);
}
};
class Solution {
public int mirrorDistance(int n) {
int reversed = 0;
int temp = n;
while (temp != 0) {
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
}
return Math.abs(n - reversed);
}
}
class Solution:
def mirrorDistance(self, n: int) -> int:
reversed_num = 0
temp = n
while temp > 0:
digit = temp % 10
reversed_num = reversed_num * 10 + digit
temp //= 10
return abs(n - reversed_num)
Approach 2: String Reversal
Convert the integer to string, reverse the string, convert back to integer, and compute the absolute difference.
Algorithm Steps
- Convert
nto string:str_n = to_string(n) - Create reversed string:
reversed_str = reverse(str_n) - Convert reversed string to integer:
reversed_n = stoi(reversed_str) - Compute
abs(n - reversed_n) - Return the result
How It Works
This approach leverages built-in string reversal functions. For n = 123:
- String: "123"
- Reversed: "321"
- Convert to int: 321
- Result: abs(123 - 321) = 198
Complexity Analysis
| Time Complexity | Space Complexity |
|---|---|
| O(d) | O(d) |
Where d is the number of digits. We need O(d) space for the string representation.
class Solution {
public:
int mirrorDistance(int n) {
string str_n = to_string(n);
string reversed_str = str_n;
reverse(reversed_str.begin(), reversed_str.end());
int reversed_n = stoi(reversed_str);
return abs(n - reversed_n);
}
};
class Solution {
public int mirrorDistance(int n) {
String str_n = Integer.toString(n);
StringBuilder sb = new StringBuilder(str_n);
String reversed_str = sb.reverse().toString();
int reversed_n = Integer.parseInt(reversed_str);
return Math.abs(n - reversed_n);
}
}
class Solution:
def mirrorDistance(self, n: int) -> int:
str_n = str(n)
reversed_str = str_n[::-1]
reversed_n = int(reversed_str)
return abs(n - reversed_n)
Approach 3: Recursive Reversal
Reverse the integer recursively by processing one digit at a time. This demonstrates recursive thinking for number manipulation problems.
Algorithm Steps
- Define helper function
reverseRecursive(num, rev) - Base case: if
num == 0, returnrev - Recursive case: extract last digit, update reversed number, recurse with remaining digits
- Main function: call helper and compute absolute difference
How It Works
Recursively builds the reversed number. For n = 123:
- reverseRecursive(123, 0) → reverseRecursive(12, 3)
- reverseRecursive(12, 3) → reverseRecursive(1, 32)
- reverseRecursive(1, 32) → reverseRecursive(0, 321)
- Return 321
Complexity Analysis
| Time Complexity | Space Complexity |
|---|---|
| O(d) | O(d) |
Where d is the number of digits. The recursion depth is d, so O(d) space for the call stack.
class Solution {
private:
int reverseRecursive(int num, int rev) {
if (num == 0) {
return rev;
}
int digit = num % 10;
return reverseRecursive(num / 10, rev * 10 + digit);
}
public:
int mirrorDistance(int n) {
int reversed = reverseRecursive(n, 0);
return abs(n - reversed);
}
};
class Solution {
private int reverseRecursive(int num, int rev) {
if (num == 0) {
return rev;
}
int digit = num % 10;
return reverseRecursive(num / 10, rev * 10 + digit);
}
public int mirrorDistance(int n) {
int reversed = reverseRecursive(n, 0);
return Math.abs(n - reversed);
}
}
class Solution:
def reverseRecursive(self, num: int, rev: int) -> int:
if num == 0:
return rev
digit = num % 10
return self.reverseRecursive(num // 10, rev * 10 + digit)
def mirrorDistance(self, n: int) -> int:
reversed_num = self.reverseRecursive(n, 0)
return abs(n - reversed_num)
Approach 4: Two-Pointer String Reversal
Use two pointers to reverse the string representation of the number, then convert back to integer.
Algorithm Steps
- Convert
nto string - Initialize two pointers:
left = 0,right = length - 1 - While
left < right, swap characters at left and right - Increment left, decrement right
- Convert reversed string to integer
- Compute absolute difference
How It Works
This is similar to Approach 2 but manually implements string reversal using two pointers instead of built-in functions.
Complexity Analysis
| Time Complexity | Space Complexity |
|---|---|
| O(d) | O(d) |
Same as string reversal approach but demonstrates manual string manipulation.
class Solution {
public:
int mirrorDistance(int n) {
string str_n = to_string(n);
int left = 0, right = str_n.length() - 1;
while (left < right) {
swap(str_n[left], str_n[right]);
left++;
right--;
}
int reversed_n = stoi(str_n);
return abs(n - reversed_n);
}
};
class Solution {
public int mirrorDistance(int n) {
char[] chars = Integer.toString(n).toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
int reversed_n = Integer.parseInt(new String(chars));
return Math.abs(n - reversed_n);
}
}
class Solution:
def mirrorDistance(self, n: int) -> int:
chars = list(str(n))
left, right = 0, len(chars) - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
reversed_n = int(''.join(chars))
return abs(n - reversed_n)
Visual Example Walkthrough
Let's trace through Approach 1 (Mathematical Reversal) with n = 123:
Original Number: 123
| Step | num | digit (num % 10) | reversed (reversed × 10 + digit) | num after (num / 10) |
|---|---|---|---|---|
| 1 | 123 | 3 | 0 × 10 + 3 = 3 | 12 |
| 2 | 12 | 2 | 3 × 10 + 2 = 32 | 1 |
| 3 | 1 | 1 | 32 × 10 + 1 = 321 | 0 |
Reversed Number: 321
Calculation
Original (n): 123
Reversed: 321
Difference: |123 - 321| = 198
Mirror Distance: 198
Edge Case: n = 10
Original: 10
Reversal process:
Step 1: digit = 0, reversed = 0
Step 2: digit = 1, reversed = 1
Reversed: 1 (not 01)
Mirror Distance: |10 - 1| = 9
Edge Case: n = 7
Original: 7
Reversal process:
Step 1: digit = 7, reversed = 7
Reversed: 7
Mirror Distance: |7 - 7| = 0
(Single-digit numbers have distance 0)
Comparison of Approaches
| Approach | Time Complexity | Space Complexity | Key Insight | Best Use Case |
|---|---|---|---|---|
| Mathematical Reversal | O(d) | O(1) | Use modulo and division to reverse digits | Optimal solution, minimal memory |
| String Reversal | O(d) | O(d) | Convert to string, reverse, convert back | Simpler code, easier to understand |
| Recursive | O(d) | O(d) | Recursive digit extraction | Demonstrating recursion skills |
| Two-Pointer String | O(d) | O(d) | Manual string reversal with two pointers | Interview demonstration of string manipulation |
Edge Cases and Testing
1. Single Digit Numbers
Input: n = 7 → Output: 0
Reversed: 7, Difference: |7 - 7| = 0
All single-digit numbers have mirror distance 0
2. Numbers Ending with Zero
Input: n = 10 → Output: 9
Reversed: 01 which is 1, Difference: |10 - 1| = 9
Important: Leading zeros are dropped when converting to integer
3. Palindromic Numbers
Input: n = 121 → Output: 0
Reversed: 121, Difference: |121 - 121| = 0
All palindromes have mirror distance 0
4. Maximum Input
Input: n = 1000000000 (10⁹) → Output: 999999999
Reversed: 1, Difference: |1000000000 - 1| = 999999999
Largest possible mirror distance
5. Minimum Input
Input: n = 1 → Output: 0
Reversed: 1, Difference: |1 - 1| = 0
6. Symmetric Numbers
Input: n = 12321 → Output: 0
Reversed: 12321, Difference: |12321 - 12321| = 0
Another palindrome example
7. Numbers with All Same Digits
Input: n = 999 → Output: 0
Reversed: 999, Difference: |999 - 999| = 0
8. Large Difference Case
Input: n = 100 → Output: 99
Reversed: 1, Difference: |100 - 1| = 99
Numbers with many trailing zeros have large mirror distance
FAQs
1. What happens when n ends with zero(s)?
When reversing numbers ending with zeros, the reversed number drops leading zeros. For example, reverse(100) = 001 which becomes 1. This is handled automatically by both mathematical and string approaches when converting back to integer.
2. Can the mirror distance be negative?
No, mirror distance is defined as the absolute difference, so it's always non-negative. The abs() function ensures this.
3. What's the time complexity in terms of n?
O(log₁₀ n) or more precisely O(d) where d is the number of digits. Since d = ⌊log₁₀ n⌋ + 1, it's logarithmic in terms of n.
4. Can we solve this without reversing the entire number?
Not really. The problem definition requires computing reverse(n), so we must reverse the digits in some form. However, we could compute the difference digit by digit without explicitly building the reversed number, but that would be more complex.
5. What if n is negative?
The constraints say 1 ≤ n ≤ 10⁹, so n is always positive. If n could be negative, we would need to handle the sign separately (e.g., reverse(-123) = -321).
6. How do we handle integer overflow?
With constraints n ≤ 10⁹, the reversed number is at most 9,000,000,001 which fits in 64-bit integer. For safety, use 64-bit integers (long long in C++, long in Java).
7. Is there a formula for mirror distance?
Not a simple closed-form formula. It depends on the specific digits of n. For two-digit numbers ab (where a and b are digits), mirror distance = |10a + b - (10b + a)| = 9|a - b|.
8. Can we use bit manipulation?
No, this is about decimal digits, not binary bits. Bit manipulation wouldn't help for reversing decimal digits.
9. What's the largest possible mirror distance?
For n in [1, 10⁹], the largest mirror distance occurs when n = 10⁹ = 1,000,000,000. reverse(1,000,000,000) = 1, so distance = 999,999,999.
10. Can we solve this with a stack?
Yes, we could push digits onto a stack and pop them to reverse, but that's essentially the same as the string or mathematical approach with extra data structure overhead.