← All problems

2337. Remove Digit from Number to Maximize Result

EasyOpen on LeetCodeProblem statement

Problem Statement

2337. Remove Digit From Number to Maximize Result

Easy


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:

Java — alternative 1

Source file
public class Solution {

    public boolean canChange(String start, String target) {
        int startLength = start.length();
        // Pointers for start string and target string
        int startIndex = 0, targetIndex = 0;

        while (startIndex < startLength || targetIndex < startLength) {
            // Skip underscores in start
            while (
                startIndex < startLength && start.charAt(startIndex) == '_'
            ) {
                startIndex++;
            }
            // Skip underscores in target
            while (
                targetIndex < startLength && target.charAt(targetIndex) == '_'
            ) {
                targetIndex++;
            }
            // If one string is exhausted, both should be exhausted
            if (startIndex == startLength || targetIndex == startLength) {
                return startIndex == startLength && targetIndex == startLength;
            }

            // Check if the pieces match and follow movement rules
            if (
                start.charAt(startIndex) != target.charAt(targetIndex) ||
                (start.charAt(startIndex) == 'L' && startIndex < targetIndex) ||
                (start.charAt(startIndex) == 'R' && startIndex > targetIndex)
            ) return false;

            startIndex++;
            targetIndex++;
        }

        // If all conditions are satisfied, return true
        return true;
    }
}