Leetcode 2259. Remove Digit From Number to Maximize Result
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 number so that the resulting value is the largest possible.
Return the resulting string representing the largest possible value.
Input: number = "123", digit = "3"
Output: "12"
Input: number = "1231", digit = "1"
Output: "231"
Input: number = "551", digit = "5"
Output: "51"
Q: Can digit appear multiple times in number?
A: Yes, digit can appear multiple times in number.
Q: What constraints should we consider regarding the length of number?
A: Typically, constraints would be mentioned in the problem. Assuming reasonable constraints (like number not longer than 10⁵).
Q: Is the input always a valid positive integer string and a single digit character?
A: Yes, the input constraints ensure number is a non-empty string of digits ('0'-'9') and digit is a single character digit ('0'-'9').
number and identify all occurrences of digit.digit.Here’s the C++ implementation of the above strategy:
#include <string>
std::string removeDigit(std::string number, char digit) {
std::string maxResult = "";
for (size_t i = 0; i < number.size(); ++i) {
if (number[i] == digit) {
// Create a new string without the i-th occurrence of 'digit'
std::string newNumber = number.substr(0, i) + number.substr(i + 1);
// Check if it's the largest we've seen
if (newNumber > maxResult) {
maxResult = newNumber;
}
}
}
return maxResult;
}
The time complexity of this solution is (O(n^2)) where (n) is the length of number:
number once, so (O(n)).digit appears at the beginning, middle, or end of the string.number efficiently.We should test the function with the following cases:
digit.digit.number being at its minimal size (e.g., “1” and digit=”1”).This provides a robust check across the range of expected inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?