imashutosh51

Remove K digits

Feb 3rd, 2026 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. """
  2. Key intuition:
  3. If a larger digit appears before a smaller digit (e.g., ... 4 3 ...),
  4. keeping the larger digit will always lead to a bigger number.
  5. Therefore, whenever we encounter such a pattern and still have removals
  6. available, it is always optimal to remove the larger digit on the left.
  7.  
  8. Approach:
  9. We use a monotonic increasing stack to build the smallest possible number.
  10. The stack maintains digits in increasing order from left to right, ensuring
  11. that higher place-value positions are as small as possible.
  12.  
  13. Algorithm:
  14. - Iterate through each digit in the number.
  15. - While the stack is not empty, removals (k) are still available, and the
  16.  top of the stack is greater than the current digit, pop the stack
  17.  (this removes a larger digit that would worsen the final number).
  18. - Push the current digit onto the stack.
  19. - After processing all digits, if removals remain, remove digits from the
  20.  end of the stack (least significant digits).
  21. - Finally, strip leading zeros. If the result is empty, return "0".
  22.  
  23. Invariant:
  24. At every step, the stack represents the smallest possible prefix that can
  25. be formed using the digits processed so far with the remaining removals.
  26. """
  27.  
  28. class Solution:
  29.     def removeKdigits(self, num: str, k: int) -> str:
  30.         st = []
  31.  
  32.         for i in num:
  33.             while st and k > 0 and st[-1] > i:
  34.                 st.pop()
  35.                 k -= 1
  36.             st.append(i)
  37.  
  38.         # If removals remain, remove from end
  39.         while k > 0:
  40.             st.pop()
  41.             k -= 1
  42.  
  43.         # Build result and remove leading zeros
  44.         result = "".join(st).lstrip('0')
  45.  
  46.         return result if result else "0"
Advertisement
Add Comment
Please, Sign In to add comment