Imagine you have a large number displayed on a screen, but you want to make it as small as possible by removing exactly k digits. How do you do it efficiently?
Given a non-negative integer num represented as a string and an integer k, remove k digits from the number so that the new number is the smallest possible. Return the new number as a string. If the new number is empty, return "0".
1 ≤ num.length ≤ 10^5num consists of only digits '0' through '9'0 ≤ k ≤ num.length
Edge cases: k equals length of num → output '0'num consists of all identical digits → remove k digits from the endnum has leading zeros after removal → remove leading zeros in output
def removeKdigits(num: str, k: int) -> str:public String removeKdigits(String num, int k)string removeKdigits(string num, int k)function removeKdigits(num, k)
def removeKdigits(num: str, k: int) -> str:
# Write your solution here
pass
class Solution {
public String removeKdigits(String num, int k) {
// Write your solution here
return "";
}
}
#include <string>
using namespace std;
string removeKdigits(string num, int k) {
// Write your solution here
return "";
}
function removeKdigits(num, k) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: 1219 (correct) but code returns 4321Not using monotonic stack; removing digits incorrectly or in wrong order.✅ Implement a stack that pops digits larger than current digit while k > 0.
Wrong: 0200 instead of 200Leading zeros not removed after digit removal.✅ Strip leading zeros from the final string or return '0' if empty.
Wrong: 11 instead of 0 when k equals num lengthNot returning '0' when all digits are removed.✅ Return '0' if the resulting string is empty after removal.
Wrong: 12 instead of 11Removing wrong digit due to incorrect greedy logic.✅ Remove digits only when next digit is smaller or from the end if none.
Wrong: TLE on large inputUsing brute force or non-linear time complexity.✅ Use O(n) monotonic stack approach to remove digits efficiently.