Java | 2 Approaches | Detailed explanation
Intution\nlet\'s say if suppose we have n digits and we have to derive the next lowest number possible after removing 1 digit, then we need to remove the first 
**Intution**\nlet\'s say if suppose we have n digits and we have to derive the next lowest number possible after removing 1 digit, then we need to **remove the first peak**, (the largest number in the first increasing sequence). \n\n1 5 **7** 6 5 4\nNext lowest number possible would be 15654\n\nNow, we have to remove k digits here. So let\'s repeat this operation k times.\nk = 3\n1 5 **7** 6 5 4\nk=2\n1 5 **6** 5 4\nk=1\n1 5 **5** 4\n\nk=0 comes out of the loop\n\n**Approach 1:**\n\n\n```\npublic String removeKdigits(String num, int k) {\n        StringBuilder sb = new StringBuilder(num);\n        while (k > 0) {\n            int i = 0;\n            //find the peak\n            while (i < sb.length() - 1\n                    && sb.charAt(i) <= sb.charAt(i + 1)) {\n                i++;\n            }\n            //delete the peak\n            sb.deleteCharAt(i);\n            k--;\n        }\n        //remove the leading 0s\n        while (sb.toString().startsWith("0")) {\n         sb.deleteCharAt(0);\n        }\n        return sb.length() == 0 ? "0" : sb.toString();\n    }\n\n\n\nThis approach is a little inefficient as it repeats the operation k times.\nTime Complexity will be O(NK).\n\n```\nHow can we improve this solution by adding an extra space?\n\nTo eliminate the peak, we can use a stack.\n\nWith the help of a stack, we can track the peak elements and easily pop them out.\n\n**Approach 2:**\n```\n\npublic String removeKdigits(String num, int k) {\n        if (k == num.length()) {\n            return "0";\n        }\n        Stack<Character> stack = new Stack<>();\n        int i = 0;\n        while (i < num.length()) {\n            //check whether the current num is smaller than the top of the stack (means we have the peak)\n            while (k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(i)) {\n                //eliminate the peak\n                stack.pop();\n                k--;\n            }\n            stack.push(num.charAt(i));\n            i++;\n        }\n        // handles the scenario where digits are equal, (1111, k=3)\n        while (k > 0 && !stack.isEmpty()) {\n            stack.pop();\n            k--;\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (!stack.isEmpty()) {\n            sb.append(stack.pop());\n        }\n        //as stack follows LIFO\n        sb.reverse();\n        \n        //remove leading zeros\n        while (sb.toString().startsWith("0")) {\n            sb.deleteCharAt(0);\n\n        }\n        return sb.length() == 0 ? "0" : sb.toString();\n    }\n\nTime Complexity: O(N)\n```\n\n\n\n\n\n\n\n\n```\n
['Stack', 'Java']