Smallest Value Achievable by Deleting K Digits

Implement removeKDigitsGreedy

Given a non-negative integer num represented as a string with no leading zeros, remove exactly k digits so that the digits left behind (in their original order) form the smallest possible number. Strip any leading zeros from the result, and return "0" if everything cancels out to zero (or nothing is left). The greedy insight: reading left to right, a digit that is immediately followed by a strictly smaller digit should always be deleted — keeping it wastes a more significant place value on a bigger number than necessary, and the smaller digit that replaces it in that position can only help. Applying that rule with a stack, one pass, is exactly equivalent to repeatedly scanning for and removing the first such digit — the stack just recognizes the opportunity the instant it appears (an "aha, this new digit is smaller than what's on top") instead of rediscovering it with a fresh scan every time.

Example 1:

Input: num = "4325043", k = 3

Output: "2043"

Example 2:

Input: num = "1234567", k = 3

Output: "1234"

Example 3:

Input: num = "10001", k = 2

Output: "0"

+ 3 hidden test cases run on Submit.

Constraints:

  • 1 ≤ num.length ≤ 12
  • num consists only of digits '0'-'9', with no leading zeros
  • 1 ≤ k ≤ num.length
  • If every digit ends up removed (or the result is all zeros), return "0"

num =

4325043

k =

3