Problem 2259

Abstract / Summary

Remove one digit from a number string to make the resulting number as large as possible.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
9 lines | 315 bytes | submitted November 3, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (200k+ submissions).

Typical patterns to solve this problem:
  • Enumeration
  • Greedy
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.74 | σ = 1.38

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
23 links | 11 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

13 solutions   November 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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