Introduction
Some problems test complex algorithms, while others focus on fundamental concepts done right.
LeetCode 3783 β Mirror Distance of an Integer falls into the second category.
This problem is simple yet important because it builds understanding of:
- Digit manipulation
- Reversing numbers
- Mathematical operations
In this article, weβll break down the problem in a clean and intuitive way, along with an optimized Java solution.
π Problem Link
LeetCode: Mirror Distance of an Integer
Problem Statement
You are given an integer n.
The mirror distance is defined as:
Where:
reverse(n)= number formed by reversing digits ofn|x|= absolute value
π Return the mirror distance.
Examples
Example 1
Input:
n = 25
Output:
27
Explanation:
reverse(25) = 52
|25 - 52| = 27
Example 2
Input:
n = 10
Output:
9
Explanation:
reverse(10) = 1
|10 - 1| = 9
Example 3
Input:
n = 7
Output:
0
Key Insight
The problem consists of two simple steps:
Intuition
Letβs take an example:
Step 1: Reverse digits
π Leading zeros are ignored automatically.
Step 2: Compute difference
Approach
Step-by-Step
- Extract digits using
% 10 - Build reversed number
- Use
Math.abs()for final result
Java Code
Dry Run
Input:
Execution:
- Reverse β 52
- Difference β |25 - 52| = 27
Complexity Analysis
Time Complexity
- Reversing number β O(d)
- (d = number of digits)
π Overall: O(log n)
Space Complexity
π O(1) (no extra space used)
Why This Works
- Digit extraction ensures correct reversal
- Leading zeros automatically removed
- Absolute difference ensures positive result
Edge Cases to Consider
- Single digit β result = 0
- Numbers ending with zero (e.g., 10 β 1)
- Large numbers (up to 10βΉ)
Key Takeaways
- Simple math problems can test core logic
- Digit manipulation is a must-know skill
- Always handle leading zeros carefully
- Use built-in functions like
Math.abs()effectively
Real-World Relevance
Concepts used here are helpful in:
- Number transformations
- Palindrome problems
- Reverse integer problems
- Mathematical algorithms
Conclusion
The Mirror Distance of an Integer problem is a great example of combining basic operations to form a meaningful solution.
While simple, it reinforces important programming fundamentals that are widely used in more complex problems.
Frequently Asked Questions (FAQs)
1. What happens to leading zeros in reverse?
They are automatically removed when stored as an integer.
2. Can this be solved using strings?
Yes, but integer-based approach is more efficient.
3. What is the best approach?
Using arithmetic operations (% and /) is optimal.




