#2710
Remove Trailing Zeros From a String
EasyStringString ManipulationTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution involves finding the last non-zero character in a single pass and slicing the string accordingly. This is efficient and avoids unnecessary operations.
⚙️
Algorithm
3 steps- 1Step 1: Start from the end of the string and find the last non-zero character.
- 2Step 2: Use the index of this character to slice the string.
- 3Step 3: Return the sliced string as the result.
solution.py7 lines
1def remove_trailing_zeros(num):
2 index = len(num) - 1
3 while index >= 0 and num[index] == '0':
4 index -= 1
5 return num[:index + 1]
6
7print(remove_trailing_zeros('51230100'))ℹ
Complexity note: The time complexity is O(n) because we traverse the string once, and slicing the string also takes O(n) in the worst case. However, we only do this once, making it efficient.
- 1Trailing zeros can be removed by identifying the last non-zero character.
- 2String slicing is a powerful tool in Python and other languages for manipulating strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.