Remove Trailing Zeros From a String - Problem
Remove Trailing Zeros From a String

You are given a positive integer represented as a string, and your task is to remove all trailing zeros from it.

๐ŸŽฏ Goal: Return the integer without any trailing zeros, still as a string.

Examples:
โ€ข Input: "12300" โ†’ Output: "123"
โ€ข Input: "10200" โ†’ Output: "102"
โ€ข Input: "123" โ†’ Output: "123" (no trailing zeros)

This problem is commonly used in string processing, number formatting, and data cleaning scenarios where you need to normalize numeric strings by removing unnecessary trailing zeros.

Input & Output

example_1.py โ€” Basic Case
$ Input: "12300"
โ€บ Output: "123"
๐Ÿ’ก Note: The input has two trailing zeros '00' that need to be removed, leaving us with '123'.
example_2.py โ€” Multiple Trailing Zeros
$ Input: "10200"
โ€บ Output: "102"
๐Ÿ’ก Note: Only the trailing zeros are removed. The zero in the middle ('102') is preserved because it's not trailing.
example_3.py โ€” No Trailing Zeros
$ Input: "123"
โ€บ Output: "123"
๐Ÿ’ก Note: Since there are no trailing zeros, the string remains unchanged.

Constraints

  • 1 โ‰ค num.length โ‰ค 1000
  • num consists of only digits
  • num represents a positive integer

Visualization

Tap to expand
Remove Trailing Zeros: Visual ProcessOriginal String:123000Scanning Process (Right to Left):Scan DirectionStep 1Step 2Step 3STOP!123000Final Result:123โœ“ "123"Algorithm Steps:1. Start from rightmost character2. While character is '0', move left3. Stop at first non-zero character4. Return substring from start to this positionTime Complexity:โ€ข Best Case: O(k) where k = trailing zerosโ€ข Worst Case: O(n) when no trailing zerosSpace Complexity:โ€ข O(1) extra space (using built-in methods)
Understanding the Visualization
1
Identify the Problem
We need to remove trailing zeros while preserving the rest
2
Choose Direction
Start from the end since that's where trailing zeros are
3
Stop at Content
As soon as we find a non-zero, we know where to cut
Key Takeaway
๐ŸŽฏ Key Insight: By scanning from right to left, we can stop as soon as we find the first non-zero character, making the algorithm more efficient for strings with many trailing zeros.
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen