11. Remove K Digits
Last updated
Last updated
The problem can be found at the following link: Question Link
Initialize a pair last with values {0, K}, where last.first represents the index and last.second represents the remaining removal count.
Iterate through the string S:
Skip leading zeros and update the last pair accordingly.
Decrement K until it becomes zero or no more leading zeros are encountered.
Break out of the loop if K becomes zero.
Create a stack num to store the digits of the final number.
Set the starting index as last.first and update K from last.second.
Iterate through the remaining characters of the string:
While the stack is not empty, the top element is greater than the current digit, and there are still removals (K), pop elements from the stack.
Push the current digit onto the stack.
Pop any remaining elements from the stack based on the remaining removals (K).
Construct the final result string by popping elements from the stack and reversing it.
If the result is an empty string, set it to "0".
Return the final result.
Time Complexity: O(N)
, where n is the length of the input string
Auxiliary Space Complexity: O(N)
, where n is the length of the input string
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.