Bird
Raised Fist0

The following code attempts to remove k digits from a number string to get the smallest number. Which line contains a subtle bug that causes incorrect results on inputs with leading zeros?

medium🐞 Bug Identification Q14 of Q15
Greedy Algorithms - Remove K Digits (Smallest Number)
The following code attempts to remove k digits from a number string to get the smallest number. Which line contains a subtle bug that causes incorrect results on inputs with leading zeros?
def removeKdigits(num: str, k: int) -> str:
    builder = []
    for digit in num:
        while k > 0 and builder and builder[-1] > digit:
            builder.pop()
            k -= 1
        builder.append(digit)
    while k > 0:
        builder.pop()
        k -= 1
    result = ''.join(builder)  # Bug here
    return result if result else '0'
ALine where digits are popped inside the for loop
BLine where leading zeros are not stripped from the final result
CLine where remaining digits are popped after the loop
DLine where digits are appended to builder
Step-by-Step Solution
  1. Step 1: Identify missing leading zero removal

    The code joins builder into a string but does not strip leading zeros, which can cause incorrect output like "0012" instead of "12".
  2. Step 2: Why this is a bug

    Leading zeros must be removed to get the correct smallest number representation; otherwise, the output is invalid.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Adding .lstrip('0') fixes the bug [OK]
Quick Trick: Always strip leading zeros before returning result [OK]
Common Mistakes:
MISTAKES
  • Forgetting to strip leading zeros
  • Removing digits incorrectly in the loop
  • Not popping remaining digits when k > 0
Trap Explanation:
PITFALL
  • Code looks correct but misses subtle string cleanup step causing wrong output.
Interviewer Note:
CONTEXT
  • Tests attention to detail and handling of edge cases in string manipulation.
Master "Remove K Digits (Smallest Number)" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes