Remove Digit From Number to Maximize Result — LeetCode 2259 Python Solution

EasyGreedyStringEnumeration
Problem
#2259
Pattern
Greedy
Reading time
2 min

The 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.

Example

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

Python solution

Python
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
        )

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2259. Remove Digit From Number to Maximize Result is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2259. Remove Digit From Number to Maximize Result?
LeetCode 2259. Remove Digit From Number to Maximize Result is rated Easy on LeetCode.
What is the time complexity of LeetCode 2259. Remove Digit From Number to Maximize Result?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2259. Remove Digit From Number to Maximize Result?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2259. Remove Digit From Number to Maximize Result cover?
LeetCode 2259. Remove Digit From Number to Maximize Result is tagged Greedy, String and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview