Bird
Raised Fist0

Which line contains a subtle bug that causes incorrect output on inputs with leading zeros?

medium🐞 Bug Identification Q7 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 output on inputs with leading zeros? ```python def removeKdigits(num: str, k: int) -> str: stack = [] for digit in num: while k > 0 and stack and stack[-1] > digit: stack.pop() k -= 1 stack.append(digit) while k > 0: stack.pop() k -= 1 result = ''.join(stack) return result if result else '0' ```
ALine that joins stack into result string without stripping zeros
BLine that pops remaining digits when k > 0 after iteration
CLine that removes digits while k > 0 and stack[-1] > digit
DLine that returns '0' if result is empty
Step-by-Step Solution
Solution:
  1. Step 1: Identify missing leading zero removal

    The code joins stack but does not strip leading zeros, causing incorrect output.
  2. Step 2: The subtle bug is in the while loop removing digits

    If digits are not removed properly when a smaller digit appears, leading zeros remain.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Leading zeros remain due to incorrect popping logic [OK]
Quick Trick: Leading zeros must be stripped after removals [OK]
Common Mistakes:
MISTAKES
  • Not stripping leading zeros
  • Removing digits from wrong positions
Trap Explanation:
PITFALL
  • Candidates often miss that popping condition must ensure smaller digits replace larger ones to remove leading zeros.
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle bugs affecting edge cases like leading zeros.
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