algoadvance

  1. Remove Trailing Zeros From a String

You are given a string num representing a large integer. Return the string after removing all trailing zeros.

Example 1:

Input: num = "51230100"
Output: "512301"
Explanation: We remove the trailing zeros and return "512301".

Example 2:

Input: num = "123"
Output: "123"
Explanation: There are no trailing zeros, so we return "123".

Clarifying Questions

  1. Is the input always a valid numeric string?
    • Yes, the problem statement implies that the input is always a valid string representing a large integer.
  2. Can the input string have leading zeros?
    • The example provided focuses on trailing zeros, so leading zeros are not specified as a concern.
  3. Should we consider the case where the entire number is zero (“000”)?
    • Yes, this should return an empty string "" since all zeros are considered trailing.

Strategy

  1. Trim Trailing Zeros:
    • We can use Python’s built-in rstrip method which removes all instances of the specified characters from the end of the string. By specifying the character '0', we can remove all trailing zeros efficiently.
  2. Return the Result:
    • Return the result after trimming the trailing zeros.

Code

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

Time Complexity

Implementing this function in an actual interview setting should be effective given the simplicity of Python’s string operations for this type of task.

Try our interview co-pilot at AlgoAdvance.com