Remove Trailing Zeros From a String — Problem & Solution
Remove Trailing Zeros From a String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Remove Trailing Zeros From a String is an easy coding problem on strings, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a positive integer represented as the string num, remove its trailing zeros and return the result.
Example 1
Input: num = "51230100"
Output: 512301
Explanation: Two trailing zeros are removed.
Example 2
Input: num = "123"
Output: 123
Explanation: There are no trailing zeros.
Example 3
Input: num = "1000"
Output: 1
Constraints
1 <= num.length <= 1000num consists of digits.num has no leading zeros.
Hints for Remove Trailing Zeros From a String
Hint 1
Walk backwards from the end while the character is
'0'.Hint 2
Slice the string at the first non-zero position from the right.
Hint 3
Interior zeros must be preserved — only the trailing run goes.
How to solve Remove Trailing Zeros From a String
Find where the trailing run of zeros begins, then cut there. One backwards scan is enough.
Approach
- Start
endat the string length. - While the character at
end - 1is'0', decrementend. - Return the prefix of length
end.
Why it works
The loop stops at the first non-zero from the right, so everything before it — including any interior zeros — is preserved exactly.
Complexity
- Time —
O(n) - Space —
O(n) for the result
Pitfalls
- Removing all zeros rather than only the trailing ones destroys
"51230100"→"5123 1". - The input has no leading zeros and is positive, so the result is never empty.
- A regex like
/0+$/works, but the manual scan makes the "trailing only" intent explicit.
Reference solution
Python
def removeTrailingZeros(num: str) -> str:
end = len(num)
while end > 0 and num[end - 1] == '0':
end -= 1
return num[:end]Java
public static String removeTrailingZeros(String num) {
int end = num.length();
while (end > 0 && num.charAt(end - 1) == '0') end--;
return num.substring(0, end);
}C++
string removeTrailingZeros(string num) {
int end = (int) num.size();
while (end > 0 && num[end - 1] == '0') end--;
return num.substr(0, end);
}JavaScript
var removeTrailingZeros = function(num) {
let end = num.length;
while (end > 0 && num.charAt(end - 1) === "0") end--;
return num.slice(0, end);
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings