Skip to content

Instantly share code, notes, and snippets.

@kenzhemir
Created May 13, 2020 22:19
Show Gist options
  • Save kenzhemir/ad08184477a2033efc98eda11e038c60 to your computer and use it in GitHub Desktop.
Save kenzhemir/ad08184477a2033efc98eda11e038c60 to your computer and use it in GitHub Desktop.
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.
Example 1:
Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
/**
* @param {string} num
* @param {number} k
* @return {string}
*/
var removeKdigits = function(num, k) {
let result = num;
let c = 0
let i = 0
while (c < k) {
if (i >= result.length-1) {
result = result.substring(0, result.length-1)
c++
} else if (result[i] > result[i+1]) {
result = result.substring(0, i) + result.substring(i+1)
i = i - 1
c++
} else {
i = i + 1
}
}
return result.replace(/^0+/, "") || "0";
};
// Runtime: 56 ms
// Memory Usage: 41.6 MB
// 94.78%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment