2710. Remove Trailing Zeros From a String
Problem Description
You are given a positive integer num
represented as a string. Your task is to remove all trailing zeros from this number and return the result as a string.
Trailing zeros are the 0
characters that appear at the end of the string. You need to remove all consecutive 0
s from the right side of the string until you encounter a non-zero digit.
For example:
- If
num = "51230100"
, the output should be"512301"
(removed two trailing zeros) - If
num = "123"
, the output should be"123"
(no trailing zeros to remove)
The solution uses Python's built-in rstrip("0")
method, which removes all occurrences of the specified character (in this case "0"
) from the right side of the string. This directly accomplishes the goal of removing trailing zeros in a single operation.
Intuition
When we need to remove trailing zeros from a string representation of a number, we're essentially looking for the rightmost non-zero digit and keeping everything up to that point.
Think about reading the string from right to left - we want to skip all the 0
s we encounter until we hit our first non-zero character. Once we find that character, we want to keep everything from the beginning of the string up to and including that character.
This is a common string manipulation pattern. Rather than manually iterating through the string from the end and tracking indices, we can leverage built-in string methods that are designed for exactly this purpose. Python's rstrip()
method removes specified characters from the right side of a string, continuing until it encounters a different character.
Since we want to remove only 0
s from the right side, rstrip("0")
perfectly matches our requirement. It will:
- Start from the rightmost character
- Remove it if it's a
0
- Continue moving left, removing
0
s - Stop when it encounters any non-zero character
- Return the resulting string
This approach is both elegant and efficient, accomplishing in one line what would otherwise require a loop with index tracking.
Solution Approach
The solution follows a straightforward traversal approach from the end of the string to find where the trailing zeros end.
The implementation uses Python's built-in rstrip("0")
method, which internally performs the following steps:
- Start from the rightmost character of the string
num
- Check if the current character is
"0"
:- If yes, remove it and move to the next character on the left
- If no, stop the process
- Return the resulting string after all trailing
"0"
s have been removed
The algorithm can be visualized as traversing the string from right to left:
- For a string like
"51230100"
, the traversal would be:- Position 7:
'0'
→ remove - Position 6:
'0'
→ remove - Position 5:
'1'
→ stop - Result:
"512301"
- Position 7:
This approach has a time complexity of O(n)
where n
is the length of the string, as in the worst case we might need to check all characters (when there are no trailing zeros). The space complexity is O(1)
if we consider the string manipulation in-place, or O(n)
if we account for the new string creation in Python.
The beauty of this solution lies in its simplicity - what could be implemented with a manual loop and index tracking is elegantly handled by a single string method that directly expresses our intent: "remove trailing zeros."
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with the example num = "51230100"
.
Step 1: Initial State
- We have the string
"51230100"
- We want to remove all trailing zeros (the zeros at the end)
Step 2: Apply rstrip("0")
The rstrip("0")
method starts examining characters from the rightmost position:
Position: 0 1 2 3 4 5 6 7 String: 5 1 2 3 0 1 0 0 ↑ Start here
Step 3: Traverse from right to left
- Position 7: Character is
'0'
→ Remove it - Position 6: Character is
'0'
→ Remove it - Position 5: Character is
'1'
→ Stop! (not a zero)
Step 4: Result
After removing the two trailing zeros, we get "512301"
Original: "51230100" Result: "512301"
Another Example: num = "1000"
- Position 3:
'0'
→ remove - Position 2:
'0'
→ remove - Position 1:
'0'
→ remove - Position 0:
'1'
→ stop - Result:
"1"
Edge Case: num = "123"
- Position 2:
'3'
→ not a zero, stop immediately - Result:
"123"
(unchanged)
The solution elegantly handles all cases with just return num.rstrip("0")
, letting Python's built-in method do the heavy lifting of identifying and removing consecutive trailing zeros.
Solution Implementation
1class Solution:
2 def removeTrailingZeros(self, num: str) -> str:
3 """
4 Remove all trailing zeros from a string representation of a number.
5
6 Args:
7 num: A string representing a number that may have trailing zeros
8
9 Returns:
10 The string with all trailing zeros removed from the right end
11 """
12 # Use rstrip to remove all occurrences of '0' from the right side of the string
13 return num.rstrip("0")
14
1class Solution {
2 /**
3 * Removes trailing zeros from a string representation of a number.
4 *
5 * @param num The input string containing a number with possible trailing zeros
6 * @return A string with all trailing zeros removed
7 */
8 public String removeTrailingZeros(String num) {
9 // Start from the last character of the string
10 int lastNonZeroIndex = num.length() - 1;
11
12 // Traverse backwards while current character is '0'
13 while (lastNonZeroIndex >= 0 && num.charAt(lastNonZeroIndex) == '0') {
14 lastNonZeroIndex--;
15 }
16
17 // Return substring from start to the last non-zero character (inclusive)
18 return num.substring(0, lastNonZeroIndex + 1);
19 }
20}
21
1class Solution {
2public:
3 /**
4 * Removes all trailing zeros from the end of a numeric string
5 * @param num - The input string representing a number
6 * @return The string with trailing zeros removed
7 */
8 string removeTrailingZeros(string num) {
9 // Continue removing characters while the last character is '0'
10 while (num.back() == '0') {
11 num.pop_back(); // Remove the last character from the string
12 }
13
14 // Return the modified string without trailing zeros
15 return num;
16 }
17};
18
1/**
2 * Removes trailing zeros from a string representation of a number
3 * @param num - The string containing the number with potential trailing zeros
4 * @returns The string with trailing zeros removed
5 */
6function removeTrailingZeros(num: string): string {
7 // Start from the last character of the string
8 let lastNonZeroIndex: number = num.length - 1;
9
10 // Move backwards while current character is '0'
11 while (lastNonZeroIndex >= 0 && num[lastNonZeroIndex] === '0') {
12 lastNonZeroIndex--;
13 }
14
15 // Return substring from start to the last non-zero character (inclusive)
16 return num.substring(0, lastNonZeroIndex + 1);
17}
18
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the string num
. The rstrip("0")
method needs to traverse the string from the right end to find and remove all trailing zeros, which in the worst case (when there are no trailing zeros) requires examining all n
characters.
The space complexity is O(1)
if we don't count the space consumed by the answer string. The rstrip()
method operates by returning a new string without the trailing zeros, but aside from this output string, no additional auxiliary space proportional to the input size is used. If we do count the output string, the space complexity would be O(n)
since in the worst case the returned string could be as long as the input string.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Handling strings that consist entirely of zeros
One critical edge case that the basic rstrip("0")
approach doesn't handle properly is when the input string contains only zeros, like "0000"
. Using rstrip("0")
would return an empty string ""
, which doesn't represent a valid number. However, mathematically, we should return "0"
to maintain a valid numeric representation.
Example of the issue:
num = "0000" result = num.rstrip("0") # Returns "" (empty string) # But we need "0" as the result
Solution:
class Solution:
def removeTrailingZeros(self, num: str) -> str:
result = num.rstrip("0")
# If the result is empty, return "0" to maintain valid number representation
return result if result else "0"
2. Misunderstanding the problem scope - decimal numbers
Developers might assume the solution should handle decimal numbers like "123.4500"
. The rstrip("0")
method would correctly remove trailing zeros after the decimal point, but if there's a decimal point followed only by zeros (like "123.000"
), you'd end up with "123."
which might not be the desired format.
Solution for decimal handling:
class Solution:
def removeTrailingZeros(self, num: str) -> str:
result = num.rstrip("0")
# Also remove trailing decimal point if present
if result.endswith("."):
result = result.rstrip(".")
return result if result else "0"
3. Not considering leading zeros
While the problem specifically asks for removing trailing zeros, developers might mistakenly think they need to handle leading zeros as well. Using strip("0")
instead of rstrip("0")
would remove both leading and trailing zeros, which changes the problem entirely.
Incorrect approach:
# Wrong - removes both leading and trailing zeros num = "00123000" result = num.strip("0") # Returns "123" - also removed leading zeros!
Correct approach stays with rstrip()
:
# Correct - only removes trailing zeros num = "00123000" result = num.rstrip("0") # Returns "00123" - preserves leading zeros
Which data structure is used to implement priority queue?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!