LeetCode 3726 - Remove Zeros in Decimal Representation
The problem gives us a positive integer n and asks us to remove every digit '0' from its decimal representation. After all zero digits have been removed, we must return the resulting value as an integer. In other words, we first view the number as a sequence of decimal digits.
Difficulty: 🟢 Easy
Topics: Math, Simulation
Solution
LeetCode 3726 - Remove Zeros in Decimal Representation
Problem Understanding
The problem gives us a positive integer n and asks us to remove every digit '0' from its decimal representation. After all zero digits have been removed, we must return the resulting value as an integer.
In other words, we first view the number as a sequence of decimal digits. Every occurrence of the digit 0 is deleted, while all other digits remain in their original order. The remaining digits are then interpreted as a new integer.
For example, if n = 1020030, its decimal representation is "1020030". Removing all zero digits leaves "123", which corresponds to the integer 123.
The input constraint is:
1 <= n <= 10^15
This tells us that the number contains at most 16 decimal digits. The input size is extremely small, so efficiency is not a concern. Any solution that processes each digit once will easily fit within the limits.
A few important observations and edge cases are worth noting:
- The input is guaranteed to be positive, so we never need to handle negative numbers.
- A number may contain no zeros at all, such as
1or987654321. In that case, the answer is the original number. - A number may contain multiple consecutive zeros, such as
100020003. All of them must be removed. - The problem guarantees that
n >= 1, so there is always at least one non-zero digit in the original number. Therefore, after removing zeros, the result will never be empty.
Approaches
Brute Force Approach
A straightforward solution is to repeatedly examine the digits of the number from right to left.
We can extract each digit using modulo and division operations. Whenever the digit is non-zero, we place it into a new number being constructed. Since digits are processed from least significant to most significant, extra bookkeeping is needed to rebuild the final number in the correct order.
This approach is correct because every digit is inspected exactly once, and only non-zero digits are copied into the result. However, the implementation becomes more complicated than necessary because we must carefully manage digit positions while reconstructing the number.
Optimal Approach
A simpler observation is that the problem is fundamentally about manipulating decimal digits, not performing arithmetic.
We can convert the integer into a string, remove every '0' character, and then convert the resulting string back into an integer.
This works because the decimal representation already contains the digits in the correct order. Removing zero characters directly mirrors the problem statement, making the solution both simple and easy to verify.
Since the number contains at most 16 digits, processing the string once is extremely efficient.
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Brute Force | O(d) | O(1) | Extract digits mathematically and rebuild the result |
| Optimal | O(d) | O(d) | Convert to string, remove '0' characters, convert back |
Where d is the number of digits in n.
Algorithm Walkthrough
Optimal Algorithm
- Convert the integer
ninto its decimal string representation. - Iterate through every character in the string.
- Keep only the characters that are not
'0'. - Combine the remaining characters into a new string.
- Convert the new string back into an integer.
- Return the resulting integer.
Why it works
The decimal representation of a number is simply an ordered sequence of digits. The problem requires removing every occurrence of the digit 0 while preserving the order of all other digits. The algorithm does exactly that by filtering out '0' characters and keeping all other digits unchanged. Therefore, the resulting string represents precisely the number obtained after removing all zeros from the original decimal representation.
Python Solution
class Solution:
def removeZeros(self, n: int) -> int:
filtered = "".join(ch for ch in str(n) if ch != "0")
return int(filtered)
The implementation first converts n into a string using str(n). A generator expression iterates through each character and keeps only those that are not '0'. The join operation combines the remaining digits into a new string.
Finally, int(filtered) converts the filtered string back into an integer and returns it.
This directly follows the algorithm described above and closely matches the wording of the problem statement.
Go Solution
import "strconv"
func removeZeros(n int64) int64 {
s := strconv.FormatInt(n, 10)
result := make([]byte, 0, len(s))
for i := 0; i < len(s); i++ {
if s[i] != '0' {
result = append(result, s[i])
}
}
ans, _ := strconv.ParseInt(string(result), 10, 64)
return ans
}
The Go solution follows the same logic as the Python version. The integer is converted to a string using strconv.FormatInt, then every non-zero character is collected into a byte slice. Finally, the filtered string is converted back to an int64 using strconv.ParseInt.
Since the input is guaranteed to contain at least one non-zero digit, the resulting string is never empty, so parsing always succeeds.
Worked Examples
Example 1
Input: n = 1020030
Initial string:
| Step | Character | Action | Result String |
|---|---|---|---|
| Start | - | Initialize | "" |
| 1 | '1' | Keep | "1" |
| 2 | '0' | Remove | "1" |
| 3 | '2' | Keep | "12" |
| 4 | '0' | Remove | "12" |
| 5 | '0' | Remove | "12" |
| 6 | '3' | Keep | "123" |
| 7 | '0' | Remove | "123" |
Final filtered string: "123"
Convert to integer:
123
Output:
123
Example 2
Input: n = 1
Initial string:
| Step | Character | Action | Result String |
|---|---|---|---|
| Start | - | Initialize | "" |
| 1 | '1' | Keep | "1" |
Final filtered string:
"1"
Convert to integer:
1
Output:
1
Complexity Analysis
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(d) | Each digit is processed once |
| Space | O(d) | A new string containing the non-zero digits is created |
Here, d represents the number of digits in n. Since the constraint limits n to at most 10^15, d is at most 16, making the algorithm effectively constant time in practice. Nevertheless, the formal complexity remains linear in the number of digits.
Test Cases
sol = Solution()
assert sol.removeZeros(1020030) == 123 # example with multiple zeros
assert sol.removeZeros(1) == 1 # smallest valid input
assert sol.removeZeros(10) == 1 # trailing zero
assert sol.removeZeros(1000) == 1 # many trailing zeros
assert sol.removeZeros(100020003) == 123 # multiple zero groups
assert sol.removeZeros(987654321) == 987654321 # no zeros present
assert sol.removeZeros(101010101) == 11111 # alternating digits and zeros
assert sol.removeZeros(900000000000000) == 9 # large value with many zeros
assert sol.removeZeros(123456789) == 123456789 # already contains no zeros
assert sol.removeZeros(1000000000000000) == 1 # upper constraint style case
| Test | Why |
|---|---|
1020030 |
Verifies removal of scattered and consecutive zeros |
1 |
Smallest valid input |
10 |
Single trailing zero |
1000 |
Multiple trailing zeros |
100020003 |
Several groups of consecutive zeros |
987654321 |
No zeros to remove |
101010101 |
Alternating zero and non-zero digits |
900000000000000 |
Large number with many zeros |
123456789 |
Identity case |
1000000000000000 |
Near maximum constraint size |
Edge Cases
Numbers With No Zeros
An input such as 987654321 contains no zero digits. A buggy implementation might accidentally modify the number even when no removal is necessary. The filtering approach naturally preserves every digit, so the original value is returned unchanged.
Numbers Ending With Many Zeros
Inputs such as 1000 or 900000000000000 contain several trailing zeros. Some arithmetic reconstruction methods can make mistakes when handling place values after removing digits. The string filtering approach simply removes all '0' characters and leaves only the meaningful digits.
Multiple Consecutive Zero Blocks
Numbers such as 100020003 contain several runs of consecutive zeros. A flawed implementation might remove only the first zero in each group or mishandle repeated zeros. Since every character is checked independently, all zero digits are removed regardless of how many appear consecutively.
Smallest Possible Input
The minimum allowed input is 1. This case verifies that the algorithm works correctly even when the number contains only a single digit. The string remains "1" after filtering, and converting it back to an integer correctly returns 1.