Search for a command to run...
Try your own input
Change the array and replay the algorithm from step one.
Initialization
A number is smaller when a bigger digit sits further left. So scan left to right and, whenever the digit we are about to add is smaller than the one on top of the stack, remove that top digit — as long as we still have removals left.
Monotonic Stack
1function removeKdigits(nums, k) {2 const st = [];//nums: 541892k: 2stack: 3 for (let i = 0; i < nums.length; i++) {4 const digit = nums[i];5 while (st.length > 0 && k > 0 && st[st.length - 1] > digit) {6 st.pop();7 k--;8 }9 st.push(digit);10 }11 while (st.length > 0 && k > 0) {12 st.pop();13 k--;14 }15 if (st.length === 0) return "0";16 let res = "";17 while (st.length > 0) res += st.pop();18 res = res.replace(/0+$/, "");19 res = res.split("").reverse().join("");20 if (res.length === 0) return "0";21 return res;22}