Skip to content

Commit b02baf2

Browse files
committedFeb 25, 2025
Add solution #402
1 parent 032fdab commit b02baf2

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,7 @@
320320
399|[Evaluate Division](./0399-evaluate-division.js)|Medium|
321321
400|[Nth Digit](./0400-nth-digit.js)|Medium|
322322
401|[Binary Watch](./0401-binary-watch.js)|Easy|
323+
402|[Remove K Digits](./0402-remove-k-digits.js)|Medium|
323324
404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy|
324325
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|
325326
407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard|

‎solutions/0402-remove-k-digits.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 402. Remove K Digits
3+
* https://leetcode.com/problems/remove-k-digits/
4+
* Difficulty: Medium
5+
*
6+
* Given string num representing a non-negative integer num, and an integer k, return
7+
* the smallest possible integer after removing k digits from num.
8+
*/
9+
10+
/**
11+
* @param {string} num
12+
* @param {number} k
13+
* @return {string}
14+
*/
15+
var removeKdigits = function(num, k) {
16+
const stack = [];
17+
18+
for (const n of num) {
19+
while (k > 0 && stack.length && stack[stack.length - 1] > n) {
20+
stack.pop();
21+
k--;
22+
}
23+
stack.push(n);
24+
}
25+
26+
while (k > 0) {
27+
stack.pop();
28+
k--;
29+
}
30+
31+
const result = stack.join('').replace(/^0+/, '');
32+
return result.length ? result : '0';
33+
};

0 commit comments

Comments
 (0)
Please sign in to comment.