Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/2259.html

2259. Remove Digit From Number to Maximize Result

  • Difficulty: Easy.
  • Related Topics: String, Greedy, Enumeration.
  • Similar Questions: Remove K Digits, Remove Vowels from a String, Second Largest Digit in a String.

Problem

You are given a string number representing a positive integer and a character digit.

Return the resulting string after removing **exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized**. The test cases are generated such that digit occurs at least once in number.

  Example 1:

Input: number = "123", digit = "3"
Output: "12"
Explanation: There is only one '3' in "123". After removing '3', the result is "12".

Example 2:

Input: number = "1231", digit = "1"
Output: "231"
Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".
Since 231 > 123, we return "231".

Example 3:

Input: number = "551", digit = "5"
Output: "51"
Explanation: We can remove either the first or second '5' from "551".
Both result in the string "51".

  Constraints:

  • 2 <= number.length <= 100

  • number consists of digits from '1' to '9'.

  • digit is a digit from '1' to '9'.

  • digit occurs at least once in number.

Solution (Java, C++, Python)

  • class Solution {
        public String removeDigit(String number, char digit) {
            int index = 0;
            int n = number.length();
            for (int i = 0; i < n; i++) {
                if (number.charAt(i) == digit) {
                    index = i;
                    if (i < n - 1 && digit < number.charAt(i + 1)) {
                        break;
                    }
                }
            }
            number = number.substring(0, index) + number.substring(index + 1);
            return number;
        }
    }
    
  • Todo
    
  • class Solution:
        def removeDigit(self, number: str, digit: str) -> str:
            return max(
                number[:i] + number[i + 1 :] for i, d in enumerate(number) if d == digit
            )
    
    ############
    
    # 2259. Remove Digit From Number to Maximize Result
    # https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/
    
    class Solution:
        def removeDigit(self, number: str, digit: str) -> str:
            res = ""
            
            for i, x in enumerate(number):
                if x == digit:
                    res = max(res, number[:i] + number[i + 1:])
            
            return res
    
    

Explain:

nope.

Complexity:

  • Time complexity : O(n).
  • Space complexity : O(n).

All Problems

All Solutions