Remove K Digits | Practice | GeeksforGeeks

Given a non-negative integer S represented as a string, remove K digits from the number so that the new number is the smallest possible.
Note : The given num does not contain any leading zero.
Example 1:
Input:
S = "149811", K = 3
Output: 111
Explanation: Remove the three digits 
4, 9, and 8 to form the new number 111
which is smallest.

Example 2:
Input:
S = "1002991", K = 3
Output: 21
Explanation: Remove the three digits 1(leading
one), 9, and 9 to form the new number 21(Note
that the output must not contain leading
zeroes) which is the smallest.

Your Task:
You don't need to read input or print anything. Your task is to complete the function removeKdigits() which takes the string S and an integer K as input and returns the new number which is the smallest possible.

Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(|S|).

Constraints:
1<=|S|<=10002
1<=K<=|S|
0
emmanueluluabuike1 month ago
Simple java solution
 
public String removeKdigits(String s, int k) {
        // code here
        Stack<Character> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        String newWord;

        for (int i = 0; i < s.length(); i++) {
            char num = s.charAt(i);
            while (k > 0 && !stack.isEmpty() && stack.peek() > num){
                stack.pop();
                k--;
            }
            if(stack.isEmpty() && num == '0')
                continue;
            stack.push(num);
        }

        while(!stack.isEmpty() && k > 0){
            stack.pop();
            k--;
        }
        
        if(stack.isEmpty())
            return "0";
        
        while(!stack.isEmpty()){
            sb.append(stack.peek());
            stack.pop();
        }

        newWord = sb.reverse().toString();
        return newWord;
    }
0
hanumanmanyam8371 month ago
class Solution {
    public String removeKdigits(String S, int K) {
        // code here
        StringBuilder sb = new StringBuilder();
        Stack<Integer>st=new Stack<>();
        for(int i=0;i<S.length();i++)
        {
            while(!st.isEmpty() && st.peek()>(S.charAt(i)-'0') && K>0)
            {
                st.pop();
                K--;
            }
            if(!st.isEmpty() || S.charAt(i)!='0')
            {
                st.push(S.charAt(i)-'0');
            }
            
        }
        while(!st.isEmpty()&&K>0)
        {
            st.pop();
            K--;
        }
        if(st.isEmpty())
        {
            return "0";
        }
        while(!st.isEmpty())
        {
            sb.append(st.pop());
        }
         String str = sb.reverse().toString();
        return str;
    }
}
0
shuklaps11191 month ago
//java Solution 0.8/1.9
 
class Solution {   public String removeKdigits(String S, int K) {       StringBuilder sb = new StringBuilder();              if(S.length()<=K){           return "0";       }              if(K==0){           return S;       }              Stack<Character> st = new Stack<>();              for(int i=0;i<S.length();i++){           char c = S.charAt(i);           while(!st.isEmpty() && K>0 && st.peek() > c){               st.pop();               K--;           }           if(!st.isEmpty() || c!='0'){               st.push(c);           }       }              while(!st.isEmpty()&&K>0){           st.pop();           K--;       }              if(st.isEmpty())           return "0";                  while(!st.isEmpty()){           sb.append(st.pop());       }              String str = sb.reverse().toString();              return str;   }}
0
prasadkandekar5552 months ago
C++ O(S) time and space solution :)
class Solution {
  public:
    string removeKdigits(string num, int k) {
        // treat ans as a stack in below for loop
        string ans = "";  
       
        for (char c : num) {
           
            // make sure digits in ans are in ascending order remove one char
            while (ans.length() && ans.back() > c && k) {
                ans.pop_back();         
                k--;                   
            }
           
            // can't have leading '0'
            if (ans.length() || c != '0') {
                ans.push_back(c); 
            }  
        }
        
        // make sure remove k digits in total
        while (ans.length() && k--) {
            ans.pop_back(); 
        }          
       
        return ans.empty() ? "0" : ans;
        
    }
};
 
-1
gulshan992 months ago
string removeKdigits(string S, int k) {
        string ans="";
        for(char c:S){
            while(ans.length() and ans.back()>c and k)
            {
                ans.pop_back();
                k--;
            }
            if(ans.length() || c!='0'){
                ans.push_back(c);
            }
        }
        while(ans.length() and k--){
            ans.pop_back();
        }
        return ans.empty()?"0":ans;
    }
-1
chessnoobdj3 months ago
C++
string removeKdigits(string S, int k) {
        int i = 0;
        stack <char> s;
        while(S[i]!='\0'){
            while(!s.empty() && s.top()>S[i] && k){
                s.pop();
                k--;
            }
            if(!s.empty() || S[i] != '0')
                s.push(S[i]);
            i++;
        }
        while(!s.empty() && k--)
            s.pop();
        string str = "";
        while(!s.empty()){
            str += s.top();
            s.pop();
        }
        reverse(str.begin(), str.end());
        if(str.empty())
            str += "0";
        return str;
    }
-1
thanoschild4 months ago
Time complexity = O(N), Space complexity = O(N)    
string removeKdigits(string S, int K) {       stack<int> st;       for(int i=0; i<S.size(); i++)       {           while(!st.empty() && st.top() > S[i] && K>0)           {               st.pop();               K--;           }           if(!st.empty() || S[i] != '0')           st.push(S[i]);       }       while(!st.empty() && K--)       {           st.pop();       }       if(st.empty())       return "0";              string ans;       while(!st.empty())       {           ans += st.top();           st.pop();       }       reverse(ans.begin(), ans.end());       return ans;   }
-1
shivambhadani1236 months ago
O(N) time and O(N) space using stack
class Solution {
  public:
    string removeKdigits(string S, int K) {
        stack<char> st;
        for(int i=0; i<S.size(); i++) {
            while(!st.empty() && st.top()>S[i] && K>0) {
                st.pop();
                K--;
            }
            if(!st.empty() || S[i]!='0') st.push(S[i]);
        }
        while(!st.empty() && K--) {;
            st.pop();
        }
        if(st.empty()) return "0";
        
        string ans;
        
        while(!st.empty()) {
            ans = st.top() + ans;
            st.pop();
        }
        return ans;
    }
};
0
shady418 months ago
shady41
Need to remove greater nos. from significant positions...
string removeKdigits(string str, int k) {        deque<char>dq;        for(char i: str){            if(dq.empty()) dq.push_back(i);            else{                while(k && !dq.empty() && dq.back()-'0'>i-'0'){                    dq.pop_back();                    k--;                }                dq.push_back(i);            }        }        while(k && !dq.empty()){            dq.pop_back();            k--;        }        while(!dq.empty() && dq.front()=='0'){            dq.pop_front();        }        string ans="";        while(!dq.empty()){            ans.push_back(dq.front());            dq.pop_front();        }        return (ans.empty())?"0":ans;    }
-1
wallflower10 months ago
wallflower
Hint :  Use the next greater element concept of stack to pop elements that are greater than the current element. Then for the remaining k, remove elements from top of stack. And return the string obtained.
https://ide.geeksforgeeks.o...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.