The Greedy Choice
In the number `432`, removing `4` yields `32`, but removing `2` yields `43`. You always want smaller digits at the most significant (leftmost) positions.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given a string representing a non-negative integer, remove exactly K digits to form the smallest possible integer.
In the number `432`, removing `4` yields `32`, but removing `2` yields `43`. You always want smaller digits at the most significant (leftmost) positions.
We use a stack to build our answer. If the current digit is smaller than the top of the stack, popping the top of the stack makes the overall number smaller!
Watch out for leading zeros (don't push '0' into an empty stack) and cases where the digits are already in increasing order (like `1234`). In the latter, you must manually pop from the end until K is 0.