Getting TLE in 2 cases

import java.util.*;
public class Main {
public static void main (String args[]) {

	Scanner sc= new Scanner(System.in);
	String num= sc.next();
	int k= sc.nextInt();

	System.out.println(removeKdigits(num,k));

}

public static String removeKdigits(String num, int k) {
    
    char arr[]= num.toCharArray();
    
    Stack<Character> st= new Stack<>();
    
    int i=0;

    while(i<arr.length){
        
        while(!st.isEmpty() && k>0 && arr[i]<st.peek()){
            st.pop();
            k--;
        }
        st.push(arr[i]);
        i++;
    }

    while(k>0){
        st.pop();
        k--;
    }
    
    String ans="";
    for(char ch:st){
        if(ans.length()==0 && ch=='0'){
            continue;
        }else{
            ans= ans+ch;
        }
        
    }
    
    if(ans.length()==0){
        ans="0";
    }

    return ans;
    
}

}

hi @ANUKUL1509
I take doubts only in C++… but u can refer this soln -->

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.