File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } num
3
+ * @param {number } k
4
+ * @return {string }
5
+ */
6
+ const removeKdigits = function ( num , k ) {
7
+ const digits = num . length - k ;
8
+ const stk = new Array ( num . length ) ;
9
+ let top = 0 ;
10
+ // k keeps track of how many characters we can remove
11
+ // if the previous character in stk is larger than the current one
12
+ // then removing it will get a smaller number
13
+ // but we can only do so when k is larger than 0
14
+ for ( let i = 0 ; i < num . length ; i ++ ) {
15
+ let c = num . charAt ( i ) ;
16
+ while ( top > 0 && stk [ top - 1 ] > c && k > 0 ) {
17
+ top -= 1 ;
18
+ k -= 1 ;
19
+ }
20
+ stk [ top ++ ] = c ;
21
+ }
22
+ // find the index of first non-zero digit
23
+ let idx = 0 ;
24
+ while ( idx < digits && stk [ idx ] === "0" ) idx ++ ;
25
+ return idx === digits ? "0" : stk . slice ( idx , digits + idx ) . join ( "" ) ;
26
+ } ;
You can’t perform that action at this time.
0 commit comments