Facebook Pixel

2119. A Number After a Double Reversal

Problem Description

This problem asks you to perform two consecutive reversals on an integer and check if you get back the original number.

When you reverse an integer, you flip all its digits from left to right. For example:

  • Reversing 2021 gives 1202
  • Reversing 12300 gives 321 (leading zeros are dropped)

The process works as follows:

  1. Start with an integer num
  2. Reverse it once to get reversed1
  3. Reverse reversed1 to get reversed2
  4. Return true if reversed2 equals the original num, otherwise return false

The key insight is understanding when leading zeros affect the result. When a number ends with zeros (like 12300), the first reversal drops those leading zeros (00321 becomes 321). When you reverse again, you can't recover those lost zeros, so you get 123 instead of the original 12300.

Therefore, the solution is elegant: a number will equal itself after two reversals if and only if:

  • The number is 0, OR
  • The number doesn't end with 0 (i.e., num % 10 != 0)

This is because only numbers ending in zero will lose information during the reversal process due to dropped leading zeros.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

Let's think about what happens during the reversal process. When we reverse a number, we're essentially reading its digits from right to left. The critical observation is that leading zeros in a number are not preserved.

Consider what happens with different types of numbers:

  • For 123: First reversal gives 321, second reversal gives 123
  • For 1200: First reversal gives 21 (not 0021), second reversal gives 12

The pattern becomes clear: we lose information only when the original number has trailing zeros. Why? Because these trailing zeros become leading zeros after the first reversal, and leading zeros are dropped in integer representation.

Think of it this way: if a number ends with zero (num % 10 == 0), that zero moves to the front after reversal and disappears. When we reverse again, we can't magically recreate that lost zero at the end.

The only exception is when num = 0 itself, because reversing 0 gives 0, and reversing again still gives 0.

So the condition for a number to remain unchanged after two reversals is simple:

  • Either it's 0 (special case)
  • Or it doesn't end with 0 (no information loss during reversal)

This leads directly to our one-line solution: return num == 0 or num % 10 != 0

Learn more about Math patterns.

Solution Approach

The solution leverages a mathematical observation rather than actually performing the reversal operations. This makes it extremely efficient with O(1) time complexity.

The implementation checks two conditions:

  1. Special case: If num == 0, return true because reversing 0 always gives 0
  2. General case: If num % 10 != 0, return true because the number doesn't end with zero

The key insight from our mathematical analysis is that a number will equal itself after two reversals if and only if it doesn't lose information during the reversal process. Information loss only occurs when trailing zeros become leading zeros (which are then dropped).

The modulo operation num % 10 gives us the last digit of the number. If this last digit is 0, we know the number ends with at least one zero and will lose information during reversal. If it's any other digit (1 through 9), no information is lost.

The beauty of this solution is that we don't need to:

  • Actually reverse the number (which would require converting to string or using division/modulo in a loop)
  • Store intermediate results
  • Handle overflow concerns from reversal

Instead, we solve the problem with a single mathematical check: num == 0 or num % 10 != 0

This approach transforms what seems like a simulation problem into a simple mathematical property check, achieving optimal O(1) time and space complexity.

Ready to land your dream job?

Unlock your dream job with a 3-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a few examples to see how our solution works:

Example 1: num = 526

  • Check: Is num == 0? No, 526 ≠ 0
  • Check: Is num % 10 != 0? Yes, 526 % 10 = 6, and 6 ≠ 0
  • Since the second condition is true, we return true
  • Verification: 526 → reverse → 625 → reverse → 526 ✓

Example 2: num = 1800

  • Check: Is num == 0? No, 1800 ≠ 0
  • Check: Is num % 10 != 0? No, 1800 % 10 = 0
  • Both conditions are false, so we return false
  • Verification: 1800 → reverse → 81 (leading zeros dropped) → reverse → 18 ✗

Example 3: num = 0

  • Check: Is num == 0? Yes!
  • Since the first condition is true, we return true
  • Verification: 0 → reverse → 0 → reverse → 0 ✓

The key insight illustrated here is that we don't actually perform any reversals. Instead, we use the mathematical property that only numbers ending in zero (except 0 itself) will lose information during the double reversal process. The modulo operation num % 10 efficiently checks the last digit without any string conversions or loops.

Solution Implementation

1class Solution:
2    def isSameAfterReversals(self, num: int) -> bool:
3        """
4        Determines if a number remains the same after two reversals.
5      
6        When a number is reversed twice:
7        - If it ends with 0 (except 0 itself), the leading 0 is lost in the first reversal
8        - Example: 1230 -> 321 -> 123 (not equal to 1230)
9        - Numbers not ending in 0 remain the same after two reversals
10        - Example: 526 -> 625 -> 526 (equal to original)
11      
12        Args:
13            num: The integer to check
14          
15        Returns:
16            True if the number remains the same after two reversals, False otherwise
17        """
18        # Special case: 0 reversed is still 0
19        # General case: numbers ending in non-zero digits preserve their value after two reversals
20        return num == 0 or num % 10 != 0
21
1class Solution {
2    public boolean isSameAfterReversals(int num) {
3        // A number remains the same after two reversals if and only if:
4        // 1. It is zero (special case: 0 reversed is still 0)
5        // 2. It has no trailing zeros (no digits are lost during reversal)
6        // 
7        // Example: 
8        // - 120 -> reverse -> 21 -> reverse -> 12 (not same, trailing zero lost)
9        // - 121 -> reverse -> 121 -> reverse -> 121 (same, no trailing zeros)
10      
11        return num == 0 || num % 10 != 0;
12    }
13}
14
1class Solution {
2public:
3    /**
4     * Checks if a number remains the same after two reversal operations.
5     * 
6     * A number stays the same after two reversals if and only if:
7     * - It is 0 (special case: 0 reversed is still 0), OR
8     * - It doesn't end with 0 (no trailing zeros to lose during reversals)
9     * 
10     * @param num The input integer to check
11     * @return true if the number remains unchanged after two reversals, false otherwise
12     */
13    bool isSameAfterReversals(int num) {
14        // Check if num is 0 (remains 0 after any reversals)
15        // OR if num doesn't end with 0 (no digits lost during reversals)
16        return num == 0 || num % 10 != 0;
17    }
18};
19
1/**
2 * Checks if a number remains the same after reversing it twice.
3 * 
4 * Logic: When a number is reversed twice, it returns to the original value
5 * EXCEPT when the number has trailing zeros (e.g., 1230 -> 321 -> 123).
6 * Special case: 0 remains 0 after any number of reversals.
7 * 
8 * @param num - The input number to check
9 * @returns true if the number is the same after two reversals, false otherwise
10 */
11function isSameAfterReversals(num: number): boolean {
12    // Check if num is 0 (always same after reversals) or
13    // if num doesn't end with 0 (no trailing zeros lost during reversal)
14    return num === 0 || num % 10 !== 0;
15}
16

Time and Space Complexity

The time complexity is O(1) because the function performs a fixed number of operations regardless of the input size. It only checks if num == 0 and calculates num % 10, both of which are constant-time operations that don't depend on the magnitude or number of digits in num.

The space complexity is O(1) because the function uses only a constant amount of extra space. No additional data structures are created, and the space used doesn't scale with the input. The function only performs simple arithmetic comparisons and returns a boolean value.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Attempting to Actually Perform the Reversals

Many developers instinctively try to implement the actual reversal logic, either through string manipulation or mathematical operations. This leads to unnecessarily complex code:

Problematic Approach:

def isSameAfterReversals(self, num: int) -> bool:
    # Unnecessary reversal implementation
    def reverse(n):
        result = 0
        while n > 0:
            result = result * 10 + n % 10
            n //= 10
        return result
  
    reversed1 = reverse(num)
    reversed2 = reverse(reversed1)
    return reversed2 == num

Issues with this approach:

  • Increases time complexity from O(1) to O(log n)
  • Requires handling potential integer overflow
  • More code means more potential for bugs
  • Misses the elegant mathematical insight

2. Forgetting the Special Case of Zero

A common mistake is writing:

def isSameAfterReversals(self, num: int) -> bool:
    return num % 10 != 0  # Wrong! Fails for num = 0

This fails because 0 % 10 == 0, which would return False, but 0 reversed twice is still 0, so it should return True.

Correct Solution: Always handle zero as a special case or use the compound condition: num == 0 or num % 10 != 0

3. Overthinking Edge Cases

Some developers worry about:

  • Negative numbers (the problem specifies non-negative integers)
  • Very large numbers causing overflow (not an issue with the modulo approach)
  • Numbers with multiple trailing zeros like 1000 (the simple check handles all cases)

Remember: The mathematical property holds for ALL cases - if a number ends with any zeros, it will lose information; otherwise, it won't. There's no need to count zeros or handle different patterns separately.

4. Misunderstanding Why the Solution Works

Without understanding the underlying principle, developers might think they need to check for palindromes or other special properties. The key insight to remember:

  • Leading zeros are dropped in integer representation
  • Only trailing zeros become leading zeros after reversal
  • Therefore, only numbers ending in zero lose information

This understanding prevents overcomplicating the solution and helps explain it clearly in interviews.

Discover Your Strengths and Weaknesses: Take Our 3-Minute Quiz to Tailor Your Study Plan:

A person thinks of a number between 1 and 1000. You may ask any number questions to them, provided that the question can be answered with either "yes" or "no".

What is the minimum number of questions you needed to ask so that you are guaranteed to know the number that the person is thinking?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More