Leetcode 2259: Remove Digit From Number to Maximize Result

grid47
grid47
Exploring patterns and algorithms
Mar 26, 2024 5 min read

You are given a string number representing a positive integer and a character digit. Your task is to remove exactly one occurrence of digit from the string number such that the resulting number, when interpreted as an integer, is maximized. The test cases are guaranteed to have at least one occurrence of digit in the string.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `number`, representing a positive integer, and a character `digit`, which is a digit to be removed from the string.
Example: number = '4598', digit = '5'
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.
Output: Return the resulting string after removing one occurrence of `digit` such that the value of the resulting string, when interpreted as an integer, is maximized.
Example: Output: '498'
Constraints:
Goal: The goal is to remove one occurrence of the specified `digit` to maximize the integer value of the resulting string.
Steps:
• Loop through the string to find the first occurrence of `digit` that, when removed, results in a larger number. This can be identified by checking the next character to see if it is larger than `digit`.
• If no such occurrence is found, remove the last occurrence of `digit` to ensure the maximum possible number.
Goal: Ensure that the solution efficiently handles strings up to 100 characters in length and only removes one occurrence of `digit`.
Steps:
• The string `number` will have a length between 2 and 100.
• There will be at least one occurrence of `digit` in `number`.
Assumptions:
• The string `number` will contain only digits from '1' to '9', and no leading zeros are allowed.
Input: number = '4598', digit = '5'
Explanation: After removing the '5' from the string '4598', the result is '498', which is the largest possible integer formed from the remaining digits.

Input: number = '9871', digit = '1'
Explanation: We can remove the '1' from '9871' to get '987', which is the maximum possible result.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus