Talentd
FleetCode
Make and follow sheets.Sign in

Remove Trailing Zeros From a String solution and explanation

EasyString4 min read79.5% acceptanceUpdated 9 Apr 2026
Remove Trailing Zeros From a String - Leetcode 2710Algorithms Casts · 4:15 · 873 viewsWatch on YouTube
9 more videos on this problem
  1. Remove Trailing Zeros From a String - Leetcode 2710Algorithms Casts · 4:15 · 873 views
  2. Remove Trailing Zeros From a String | Leetcode 2710 | Weekly 347Tech Courses · 1:29 · 771 views
  3. Leetcode | 2710. Remove Trailing Zeros From a String | Easy | Java SolutionDeveloper Docs · 3:43 · 722 views
  4. Leetcode Weekly contest 347 - Easy - Remove Trailing Zeros From a StringPrakhar Agrawal · 2:32 · 414 views
  5. 2710. Remove Trailing Zeros From a String (Leetcode Easy)Programming Live with Larry · 2:06 · 392 views
  6. 6457. Remove Trailing Zeros From a String | Leetcode Weekly Contest 347 | Solution Code.Optimization · 0:16 · 321 views
  7. Remove trailing zeros from a string | Weekly Contest 347 | LeetCode | DCC NIT-ADCC NITA · 1:48 · 172 views
  8. L540, №2710. Remove Trailing Zeros From a String / LeetcodeYersham · 38:55 · 130 views
  9. Remove Trailing Zeros From A String | LeetCode | Backward Iterating Approach #algorithm #leetcodeCode Divinity · 5:34 · 125 views
  10. 2710.Remove Trailing zeros from a string | LeetCode prblm |Strings |DSACode Galaxy · 1:24 · 118 views

The problem

Given a positive integer num represented as a string, return the integer num without trailing zeros as a string.

Example 1:

Input: num = "51230100"
Output: "512301"
Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".

Example 2:

Input: num = "123"
Output: "123"
Explanation: Integer "123" has no trailing zeros, we return integer "123".

Constraints:

  • 1 <= num.length <= 1000
  • num consists of only digits.
  • num doesn't have any leading zeros.

Approach overview

Problem Overview: You receive a numeric string and must return the same number after removing all trailing '0' characters. Only zeros at the end should be removed. Zeros that appear in the middle or beginning must remain unchanged.

This is a classic string processing task. The core idea is identifying the last non-zero character and returning the substring up to that position.

Approach 1: Reverse and Trim Approach (O(n) time, O(n) space)

This approach reverses the string so trailing zeros become leading zeros. Once reversed, you iterate from the start and skip all leading '0' characters. After locating the first non-zero digit, take the remaining substring and reverse it again to restore the original order.

The key idea is transforming the problem: removing trailing characters becomes removing leading characters after reversal. This technique is common in string manipulation problems where operations at the end of the string are easier from the front.

The downside is extra memory usage. Reversing the string creates intermediate strings, which increases space complexity to O(n). The time complexity is still O(n) because each character is processed a constant number of times.

Approach 2: Iterative from Back to Front (O(n) time, O(1) space)

This is the most direct solution. Start from the last character of the string and move backward while the current character equals '0'. Stop when you encounter the first non-zero digit or reach the beginning of the string.

The index where this scan stops marks the last digit that should remain. Return the substring from the start of the string up to that index (inclusive). This avoids reversing or creating unnecessary intermediate strings.

This method effectively simulates a two‑pointer style scan from the end, though only one pointer is needed. The string is traversed at most once, giving O(n) time complexity. Since only a few variables are used, the extra space remains O(1).

This pattern appears frequently in string and array problems where irrelevant elements accumulate at the end. Scanning backward is often simpler than restructuring the entire sequence.

Recommended for interviews: The Iterative from Back to Front approach is what interviewers expect. It shows you recognize the simplest possible traversal and avoid unnecessary operations like reversing the string. Mentioning the reverse approach first demonstrates understanding of alternative transformations, but the backward scan highlights strong problem‑solving instincts and optimal space usage.

Approach 1: Reverse and Trim Approach

This approach involves reversing the string so that trailing zeros become leading zeros. Then, remove those leading zeros until reaching a non-zero character, and finally reverse the result back.

This method is straightforward due to simplicity in string manipulation when leading operations are involved.

def remove_trailing_zeros(num: str) -> str:
    return num.rstrip('0')

num = "51230100"
print(remove_trailing_zeros(num))
public class RemoveTrailingZeros {
    public static String removeTrailingZeros(String num) {
        int index = num.length() - 1;
        while (index >= 0 && num.charAt(index) == '0') {
            index--;
        }
        return num.substring(0, index + 1);
    }

    public static void main(String[] args) {
        String num = "51230100";
        System.out.println(removeTrailingZeros(num));
    }
}
#include <iostream>
#include <string>
using namespace std;

string removeTrailingZeros(string num) {
    int idx = num.length() - 1;
    while (idx >= 0 && num[idx] == '0') {
        idx--;
    }
    return num.substr(0, idx + 1);
}

int main() {
    string num = "51230100";
    cout << removeTrailingZeros(num) << endl;
    return 0;
}
function removeTrailingZeros(num) {
    return num.replace(/0+$/, '');
}

let num = "51230100";
console.log(removeTrailingZeros(num));
#include <stdio.h>
#include <string.h>

void removeTrailingZeros(char *num) {
    int len = strlen(num);
    int i = len - 1;
    while (i >= 0 && num[i] == '0') {
        num[i] = '\0';
        i--;
    }
}

int main() {
    char num[] = "51230100";
    removeTrailingZeros(num);
    printf("%s\n", num);
    return 0;
}
using System;

public class RemoveTrailingZeros {
    public static string RemoveZeros(string num) {
        int index = num.Length - 1;
        while (index >= 0 && num[index] == '0') {
            index--;
        }
        return num.Substring(0, index + 1);
    }

    public static void Main(string[] args) {
        string num = "51230100";
        Console.WriteLine(RemoveZeros(num));
    }
}

In Python, the rstrip function optimizes trailing character removal by stripping away the '0' characters from the end of the string directly.

Complexity

Time Complexity: O(n), since rstrip may need to inspect all characters.
Space Complexity: O(1) as it performs modification in place.

Try this approach in the editor

Approach 2: Iterative from Back to Front

This approach discards trailing zeros by counting them from the end until a non-zero character appears, leading to a substring from the beginning up to this position.

def remove_trailing_zeros(num: str) -> str:
    index = len(num) - 1
    while index >= 0 and num[index] == '0':
        index -= 1
    return num[:index + 1]

num = "51230100"
print(remove_trailing_zeros(num))
public class RemoveTrailingZeros {
    public static String removeTrailingZeros(String num) {
        int index = num.length() - 1;
        while (index >= 0 && num.charAt(index) == '0') {
            index--;
        }
        return num.substring(0, index + 1);
    }

    public static void main(String[] args) {
        String num = "51230100";
        System.out.println(removeTrailingZeros(num));
    }
}
#include <iostream>
#include <string>
using namespace std;

string removeTrailingZeros(string num) {
    size_t pos = num.find_last_not_of('0');
    return num.substr(0, pos + 1);
}

int main() {
    string num = "51230100";
    cout << removeTrailingZeros(num) << endl;
    return 0;
}
function removeTrailingZeros(num) {
    let index = num.length - 1;
    while (index >= 0 && num.charAt(index) === '0') {
        index--;
    }
    return num.substring(0, index + 1);
}

let num = "51230100";
console.log(removeTrailingZeros(num));
#include <stdio.h>
#include <string.h>

char* removeTrailingZeros(char *num) {
    int len = strlen(num) - 1;
    while (len >= 0 && num[len] == '0') {
        len--;
    }
    num[len + 1] = '\0';
    return num;
}

int main() {
    char num[] = "51230100";
    printf("%s\n", removeTrailingZeros(num));
    return 0;
}
using System;

public class RemoveTrailingZeros {
    public static string RemoveZeros(string num) {
        int index = num.Length - 1;
        while (index >= 0 && num[index] == '0') {
            index--;
        }
        return num.Substring(0, index + 1);
    }

    public static void Main(string[] args) {
        string num = "51230100";
        Console.WriteLine(RemoveZeros(num));
    }
}

Direct indexing in Python reads clearly while simply mimicking manual movements equate efficiency by returning a sliced impression.

Complexity

Time Complexity: O(n).
Space Complexity: O(1) for no extra data paint.

Try this approach in the editor

Approach 3: Traversal

We can traverse the string from the end to the beginning, stopping when we encounter the first character that is not 0. Then, we return the substring from the beginning to this character.

The time complexity is O(n), where n is the length of the string. Ignoring the space consumed by the answer string, the space complexity is O(1).

function removeTrailingZeros(num: string): string {
    let i = num.length - 1;
    while (num[i] === '0') {
        --i;
    }
    return num.substring(0, i + 1);
}
func removeTrailingZeros(num string) string {
	i := len(num) - 1
	for num[i] == '0' {
		i--
	}
	return num[:i+1]
}
impl Solution {
    pub fn remove_trailing_zeros(num: String) -> String {
        let mut i = num.len() - 1;

        while num.chars().nth(i) == Some('0') {
            i -= 1;
        }

        num[..i + 1].to_string()
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Reverse and Trim Approach

Time Complexity: O(n), since rstrip may need to inspect all characters.
Space Complexity: O(1) as it performs modification in place.

Iterative from Back to Front

Time Complexity: O(n).
Space Complexity: O(1) for no extra data paint.

Traversal–

Complexity analysis

ApproachTimeSpaceWhen to Use
Reverse and Trim ApproachO(n)O(n)When using built-in reverse operations or when handling leading-character trimming patterns
Iterative from Back to FrontO(n)O(1)Best general solution; minimal memory and straightforward logic

Frequently asked questions

Is Remove Trailing Zeros From a String easy or hard?

Remove Trailing Zeros From a String is categorized as an Easy problem. It focuses on basic string traversal and boundary conditions rather than complex algorithms or data structures.

Remove Trailing Zeros From a String Python/Java solution

In Python or Java, iterate from the last index of the string and decrement the pointer while the character equals '0'. After the loop ends, return the substring up to the final index. The implementation is short and runs in O(n) time with constant extra space.

How to solve Remove Trailing Zeros From a String in O(n)?

Start from the last character of the string and move backward while characters equal '0'. When the first non-zero digit appears, stop the scan and return the substring from index 0 to that position. Each character is checked at most once, giving O(n) time complexity.

What is the best approach for Remove Trailing Zeros From a String?

The best approach is scanning the string from the end until the first non-zero character appears. Once found, return the substring up to that index. This solution runs in O(n) time and uses O(1) extra space, making it both simple and optimal.

Is Remove Trailing Zeros From a String asked at Google/Amazon/Meta?

String manipulation problems like this appear frequently in coding interviews at companies such as Amazon, Google, and Meta. While the exact problem may vary, identifying and trimming characters from the end of a string is a common interview pattern.

What data structure is used in Remove Trailing Zeros From a String?

The problem primarily uses basic string operations. The algorithm relies on index traversal of a string rather than specialized data structures, though the logic resembles a backward pointer scan commonly used in two-pointer techniques.

What is the time complexity of Remove Trailing Zeros From a String?

The optimal algorithm runs in O(n) time, where n is the length of the string. In the worst case you scan the entire string when it contains only zeros or when no trailing zeros exist. Space complexity can be O(1) if you only track an index while scanning backward.

Comments

Now write it yourselfClose this page and solve Remove Trailing Zeros From a String in the editor, without looking.
Practise Remove Trailing Zeros From a String