#7
Reverse Integer
MediumMathHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Mathematical Approach)★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of converting to strings, we can reverse the integer mathematically by extracting digits one by one. This is more efficient and avoids the overhead of string manipulation.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a variable to hold the reversed number (reversed = 0).
- 2Step 2: While x is not 0, extract the last digit (digit = x % 10).
- 3Step 3: Update the reversed number (reversed = reversed * 10 + digit).
- 4Step 4: Check for overflow before updating reversed. If it overflows, return 0.
- 5Step 5: Remove the last digit from x (x = x // 10).
- 6Step 6: Continue until x is 0, then return reversed.
solution.py2 lines
1# Full working Python code with comments
2ℹ
Complexity note: The time complexity is O(n) because we are processing each digit of the number once. The space complexity is O(1) since we are using a fixed amount of space regardless of the input size.
- 1Recognizing that reversing an integer can be done mathematically without converting to strings is key. This leads to a more efficient solution.
- 2Understanding the importance of checking for overflow at each step can prevent errors and ensure the solution adheres to constraints.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.