3783. Mirror Distance of an Integer

Difficulty: Easy
Topics: Math, Number Manipulation
Companies: Google, Meta, Amazon
Acceptance Rate: 86.7%
Mirror Distance visualization
Pro Tip: This is a straightforward problem that tests basic number manipulation skills. The key is to reverse the digits of the integer correctly, handling potential edge cases like numbers ending with zeros. The mathematical approach using modulo and division is optimal with O(d) time where d is the number of digits.

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.

Problem Link: View on LeetCode ↗

Key Insight

The solution requires understanding these crucial observations:

  1. We need to reverse the digits of the integer n
  2. The reversal should ignore leading zeros in the result (e.g., reverse(10) = 1, not 01)
  3. We need to compute the absolute difference between the original and reversed numbers
  4. For single-digit numbers or palindromic numbers, the mirror distance will be 0
  5. 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.

Important: The constraint 1 ≤ n ≤ 10⁹ means we don't have to worry about overflow when reversing (max reversed number would be 9,000,000,001 which fits in 64-bit integer). However, in languages with 32-bit integers, we should use 64-bit integers for safety.

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

  1. Initialize reversed = 0 and create a copy temp = n
  2. While temp > 0:
    • Extract last digit: digit = temp % 10
    • Append to reversed: reversed = reversed * 10 + digit
    • Remove last digit: temp = temp / 10
  3. Compute abs(n - reversed)
  4. Return the result

How It Works

This approach builds the reversed number digit by digit. For example, for n = 123:

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.

Mathematical Reversal Approach (Your Solution)
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)
Optimal Solution: This approach is optimal with O(d) time and O(1) space. It works by extracting digits from the end of the number and building the reversed number. Note that the mathematical approach automatically handles leading zeros correctly (e.g., 10 becomes 1, not 01).

Approach 2: String Reversal

Convert the integer to string, reverse the string, convert back to integer, and compute the absolute difference.

Algorithm Steps

  1. Convert n to string: str_n = to_string(n)
  2. Create reversed string: reversed_str = reverse(str_n)
  3. Convert reversed string to integer: reversed_n = stoi(reversed_str)
  4. Compute abs(n - reversed_n)
  5. Return the result

How It Works

This approach leverages built-in string reversal functions. For n = 123:

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.

String Reversal Approach
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)
String Approach: This approach is simpler to understand but uses extra space for the string. It's good for interviews to show multiple approaches. Note that string reversal automatically handles leading zeros correctly (e.g., "10" reversed is "01", which when converted to int becomes 1).

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

  1. Define helper function reverseRecursive(num, rev)
  2. Base case: if num == 0, return rev
  3. Recursive case: extract last digit, update reversed number, recurse with remaining digits
  4. Main function: call helper and compute absolute difference

How It Works

Recursively builds the reversed number. For n = 123:

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.

Recursive Approach
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)
Recursive Insight: This approach demonstrates recursive thinking but is less efficient in space due to recursion depth. It's useful for understanding recursion but not optimal for production code.

Approach 4: Two-Pointer String Reversal

Use two pointers to reverse the string representation of the number, then convert back to integer.

Algorithm Steps

  1. Convert n to string
  2. Initialize two pointers: left = 0, right = length - 1
  3. While left < right, swap characters at left and right
  4. Increment left, decrement right
  5. Convert reversed string to integer
  6. 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.

Two-Pointer String Reversal
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)
Two-Pointer Insight: This approach is useful for demonstrating manual string reversal techniques. It's a common pattern that appears in many string manipulation problems.

Visual Example Walkthrough

Let's trace through Approach 1 (Mathematical Reversal) with n = 123:

1
2
3

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
3
2
1

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)

Visual Insight: The mathematical reversal approach builds the reversed number digit by digit from the end. It automatically handles leading zeros correctly because the reversed integer doesn't preserve them (e.g., 10 reversed becomes 1, not 01).

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
Recommendation: For interviews and practical use, the Mathematical Reversal approach (Approach 1) is optimal in both time and space complexity. It's efficient and demonstrates strong number manipulation skills. The String approach is acceptable for most cases and can be easier to explain.

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
Important: Watch out for integer overflow when reversing. While the constraints (n ≤ 10⁹) guarantee the reversed number fits in 32-bit integer (max reversed would be 9,000,000,001 which fits in 64-bit), it's good practice to use 64-bit integers if the constraints were larger.

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.

About Algopush: Algopush provides comprehensive algorithm solutions and explanations for coding interview preparation. Visit algopush.com for more problem solutions and coding resources.