Easy to understand with explanation c++ solution in O(kn) time complexity
\nBefore I dive into the solution lets see some of the examples which will \nhelp us in reaching the correct algorithm.\n\nExample 1: Suppose the number is 1234
```\nBefore I dive into the solution lets see some of the examples which will \nhelp us in reaching the correct algorithm.\n\nExample 1: Suppose the number is 12345 and k is 1. Now we can have below cases:\nRemove 1 \u2014 Result will be 2345\nRemove 2 \u2014 Result will be 1345\nRemove 3 \u2014 Result will be 1245\nRemove 3 \u2014 Result will be 1235\nRemove 5 \u2014 Result will be 1234\n\nAs you can see in this case we get the minimum number \nwhen we delete the last digit.\n\nNow lets consider another example:\n\nExample 2 : Suppose the number is 12145 and k is 1. Now we can have below cases:\nRemove 1 \u2014 Result will be 2145\nRemove 2 \u2014 Result will be 1145\nRemove 1 \u2014 Result will be 1245\nRemove 4 \u2014 Result will be 1215\nRemove 5 \u2014 Result will be 1214\n\nIn this case we get the lowest digit if we remove 2 because the number \nnext to it is smaller than 2. After observing the two examples we can say \nthat if all the digits are in increasing order than we will delete the last digit, \notherwise we will delete a digit for which next digit is smaller. Lets consider \none more example to get a solid grasp of this:\n\nSuppose the number is 10354 and k is 2 , that means we need to delete two digits.\nWe will start iterating the number and we will see that the number next to 1 is \nsmaller than it. so we will remove 1.\n\nNow the number becomes 0354. We will again start iterating it from 0.\n\n3 is greater than 0 so move next\n5 is greater than 3 so move next\n4 is less than 5 so delete 5\n\nNow the number will become 034. Keep in mind that before returning we \nneed to remove all leading zeroes.\n\nHere is the c++ implementation of the above approach\n\n\n```\n```\nclass Solution {\npublic:\n    string removeKdigits(string num, int k) {\n        string res = "";\n        for(char &c : num){\n            while(res.size() && res.back() > c && k){\n                res.pop_back();\n                k--;\n            }\n            if(res.size() || c != \'0\')\n                res.push_back(c);\n        }\n        while(res.size() && k--){\n            res.pop_back();\n        }\n        if(res.length() == 0)\n            res.push_back(\'0\');\n        return res;\n    }\n};\n
[]