402. Remove K Digits
Asked at 21Amazon47Google45Bloomberg42Microsoft41Meta35Coupang87EPAM Systems51PhonePe83Snap80Zeta64josh technology58Zopsmart57Adobe55Deloitte50ByteDance50Accenture44Walmart Labs43Zoho42TikTok41Snowflake39Oracle35
Problem
num is a non-negative integer as a string. Remove exactly k digits to make the remaining number as small as possible, and return it without leading zeros ("0" if nothing remains).
Example: num = "1432219", k = 3 → "1219"; num = "10200", k = 1 → "200"
Constraints: length ≤ 10⁵.
To minimize the number, a larger digit followed by a smaller one should go. Keep an increasing stack; pop while the top is bigger than the incoming digit and removals remain. Remove leftovers from the end; strip leading zeros.
num 1432219, k=3
1 -> 14 -> 13 (pop 4) -> 12 (pop 3) -> 122 -> 121 (pop 2) -> 1219
Complexity: O(n).
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
st = []
for d in num:
while k and st and st[-1] > d:
st.pop()
k -= 1
st.append(d)
if k:
st = st[:-k]
return "".join(st).lstrip("0") or "0"
assert Solution().removeKdigits("1432219", 3) == "1219"
assert Solution().removeKdigits("10200", 1) == "200"
assert Solution().removeKdigits("10", 2) == "0"
class Solution {
public String removeKdigits(String num, int k) {
StringBuilder st = new StringBuilder();
for (char d : num.toCharArray()) {
while (k > 0 && st.length() > 0 && st.charAt(st.length() - 1) > d) { st.deleteCharAt(st.length() - 1); k--; }
st.append(d);
}
st.setLength(st.length() - k);
int i = 0;
while (i < st.length() && st.charAt(i) == '0') i++;
return i == st.length() ? "0" : st.substring(i);
}
}
func removeKdigits(num string, k int) string {
st := []byte{} // increasing digits
for i := 0; i < len(num); i++ {
for k > 0 && len(st) > 0 && st[len(st)-1] > num[i] {
st = st[:len(st)-1]
k--
}
st = append(st, num[i])
}
st = st[:len(st)-k]
res := strings.TrimLeft(string(st), "0")
if res == "" {
return "0"
}
return res
}