#402
Medium Algorithms Remove k digits
String Stack Greedy Monotonic Stack
36.4% acceptance
Jan 13, 2026
10530
546
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn remove_kdigits(num: String, k: i32) -> String {
let mut k = k as usize;
let mut stack: Vec<char> = Vec::new();
for ch in num.chars() {
while k > 0 && !stack.is_empty() && stack.last().unwrap() > &ch {
stack.pop();
k -= 1;
}
stack.push(ch);
}
while k > 0 {
stack.pop();
k -= 1;
}
let result: String = stack.into_iter()
.skip_while(|&c| c == '0')
.collect();
if result.is_empty() {
"0".to_string()
} else {
result
}
}
}