#include <algorithm>
#include <string>
#include <vector>

class Solution {
    static bool nonZero(char c) { return c != '0'; }

  public:
    std::string removeKdigits(const std::string &num, int k) {
        if (static_cast<int>(num.size()) <= k) {
            return "0";
        }

        std::vector<char> digits;
        for (auto d : num) {
            while (k > 0 && !digits.empty() && d < digits.back()) {
                --k;
                digits.pop_back();
            }
            digits.push_back(d);
        }

        while (k-- > 0) {
            digits.pop_back();
        }

        if (auto it = std::find_if(digits.begin(), digits.end(), nonZero);
            it != digits.end()) {
            return std::string(it, digits.end());
        }

        return "0";
    }
};

#ifdef _MF_TEST
#include <gtest/gtest.h>

TEST(examples, no_1) {
    Solution s;
    EXPECT_EQ(s.removeKdigits("1432219", 3), "1219");
}
TEST(examples, no_2) {
    Solution s;
    EXPECT_EQ(s.removeKdigits("10200", 1), "200");
}
TEST(examples, no_3) {
    Solution s;
    EXPECT_EQ(s.removeKdigits("10", 2), "0");
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
#endif