6ms Java Solution with detailed comment
\npublic class Solution {\n    public String removeKdigits(String num, int k) {\n        int remain = num.length() - k;\n        char[] numArray = num.toCharArr
```\npublic class Solution {\n    public String removeKdigits(String num, int k) {\n        int remain = num.length() - k;\n        char[] numArray = num.toCharArray(), res = new char[remain];\n        int index = 0;\n        for(int i = 0; i < numArray.length; i++) {\n            // (1)  (n - i > remain - index): have enough remaining digits to be compared\n            // (2)  (res[index - 1] > nums[i]): at this time, the (index-1) is the newest added digit,\n            //      compare this digit with the current num, if the res is greater and you have enough \n            //      remaining digits to be compared, decrease the index(it ensures that the future added digit is \n            //      always smaller than before and the size is remain) until get the right and 'safe' position\n            while((numArray.length - i > remain - index) && (index > 0 && numArray[i] < res[index - 1])) index--;\n            if(index < remain) res[index++] = numArray[i];\n        }\n        \n        // check leading zeroes\n        index = -1;\n        while(++index < remain) {\n            if(res[index] != '0') break;\n        }\n        String s = new String(res).substring(index);\n        \n        return s.length() == 0 ? "0" : s;\n    }\n}\n```
[]