1. Iterative Peak Removal
Intuition
Repeatedly find the first digit that is greater than the digit following it, delete that digit, and repeat k times.
Algorithm
- Step 1: Repeat
ktimes: find the first indexiwherenum[i] > num[i+1]. - Step 2: If no such index exists (digits are non-decreasing), remove the last character.
- Step 3: Delete the character at index
i. - Step 4: After
kremovals, strip leading zeros. - Step 5: Return
'0'if string is empty, otherwise return the cleaned string.
#include <iostream>#include <string> class Solution {public: std::string removeKdigits(std::string num, int k) { while (k > 0 && !num.empty()) { size_t i = 0; while (i + 1 < num.size() && num[i] <= num[i + 1]) { i++; } num.erase(i, 1); k--; } size_t start = num.find_first_not_of('0'); if (start == std::string::npos) return "0"; return num.substr(start); }}; int main() { Solution solver; std::cout << "Output: " << solver.removeKdigits("1432219", 3) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(K * N)— In each of the K steps, scan the string to find the first peak (num[i] > num[i+1]) and delete it, shifting string elements. - Space complexity:
O(N)— O(N) space for intermediate string copies.
Why Brute Force Doesn't Scale:
For N = 100,000 and K = 50,000, naive O(K * N) takes 5 * 109 ops (severe TLE).
Monotonic Stack processes 100,000 digits in a single pass in ~8ms.