Python 2259.py
class Solution:
def removeDigit(self, number: str, digit: str) -> str:
# brute-force
result = ""
for i, c in enumerate(number):
if c == digit:
compare = number[:i] + number[i + 1:]
result = max(result, compare)
return result
Difficulty
and has an acceptance rate of about 49% (200k+ submissions).
Typical patterns to solve this problem:
- Enumeration
- Greedy
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method removeDigit. The method receives a numeric string number and a single-character string digit. Its purpose is to delete exactly one occurrence of digit from number and return the largest possible resulting string when compared lexicographically. The algorithm follows a straightforward brute-force strategy: it examines every position where digit appears, constructs the candidate string without that character, and keeps the maximum candidate encountered.
Key Steps
The core of the algorithm consists of three distinct operations that are executed for each character in the input string.
Iteration over the input
for i, c in enumerate(number):
if c == digit:
...
The loop walks through number while tracking both the index i and the character c. The conditional if c == digit filters the positions that are eligible for removal, ensuring that only actual occurrences of the target digit are considered.
Construction of a candidate string
compare = number[:i] + number[i + 1:]
When a matching digit is found, the code builds a new string compare by concatenating the slice before the index i with the slice after it. This operation effectively removes the character at position i. Because Python slicing creates new string objects, the operation runs in time proportional to the length of number, but it is performed only for the relatively few positions where the digit occurs.
Selection of the best candidate
result = max(result, compare)
The built-in max function is used to keep the lexicographically greatest string seen so far. The initial value of result is the empty string, so the first candidate automatically becomes the current best. Subsequent candidates are compared against the stored best, and the larger one replaces it. Leveraging max avoids manual character-by-character comparison and benefits from the highly optimized C implementation inside the Python interpreter.
Edge Cases Handled
The algorithm naturally accommodates several boundary conditions without additional code.
When the target digit appears multiple times, each occurrence is examined in turn, guaranteeing that the optimal removal position is not missed.
If the digit does not occur at all, the loop never updates result, and the method returns an empty string, which aligns with the specification that exactly one digit must be removed.
A single-character input where the only character equals digit results in the removal of that character, leaving an empty string as the correct maximal outcome.
Leading zeros that may appear after removal are treated as ordinary characters; the lexicographic comparison performed by max correctly ranks strings with different numbers of leading zeros.
When all characters are identical to digit, each removal yields the same candidate string (the original string minus one character). The repeated max calls simply retain that identical value.
Performance Optimizations Observed
Although the algorithm is conceptually brute-force, it incorporates a few practical efficiencies.
The use of Python’s native slicing (number[:i] and number[i + 1:]) and string concatenation is executed in compiled code, making each candidate construction faster than an equivalent manual loop.
Employing the built-in max function for comparison leverages the interpreter’s internal optimizations for string ordering, avoiding the overhead of custom comparison logic.
By restricting candidate generation to positions where the digit actually matches, the method skips unnecessary work for characters that cannot be removed, reducing the number of slice operations proportionally to the frequency of the target digit rather than the total length of the string.
Overall, the solution runs in linear time relative to the length of number, with a small constant factor contributed by the efficient built-in operations.
ELI5 - Simplified Explanation
Imagine you have a long string of colorful number blocks sitting in a line. This code is like a little helper that wants to make the biggest number possible by taking away just one of your blocks.
The helper starts looking at the line of blocks one by one. Every time it finds a block that matches the specific number you told it to look for, it carefully sets that block aside. Once the block is gone, it looks at the new, slightly shorter line of blocks that remains.
It holds onto this new line and compares it to any other lines it has already made to see which one looks like the biggest numerical value. It keeps repeating this process until it has checked every spot where that specific number was hiding. After looking at all the options, it knows exactly which version is the absolute largest.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | Java | Python | C++ | TS | ||||
| WalkCCC | Java | Python | C++ | ||||||
| leetcode.ca | Java | Python | C++ | Go | PHP | TS | |||
| Progiez | Java | Python | C++ | ||||||
| github | charles-wangkai | Java | |||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 402: Remove K Digits
- problem 1796: Second Largest Digit in a String
- problem 2844: Minimum Operations to Make a Special Number
Solved On The Same Day
- problem 1317: Convert Integer to the Sum of Two No-Zero Integers
- problem 1417: Reformat The String
- problem 1556: Thousand Separator
- problem 1790: Check if One String Swap Can Make Strings Equal
- problem 2582: Pass the Pillow
- problem 2605: Form Smallest Number From Two Digit Arrays
- problem 2729: Check if The Number is Fascinating
- problem 881: Boats to Save People
- problem 1503: Last Moment Before All Ants Fall Out of a Plank
- problem 1578: Minimum Time to Make Rope Colorful
- problem 1685: Sum of Absolute Differences in a Sorted Array
- problem 1701: Average Waiting Time
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality