Skip to content

Commit ac59868

Browse files
authored
Create 2030-smallest-k-length-subsequence-with-occurrences-of-a-letter.js
1 parent 1f1d966 commit ac59868

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} k
4+
* @param {character} letter
5+
* @param {number} repetition
6+
* @return {string}
7+
*/
8+
const smallestSubsequence = function (s, k, letter, repetition) {
9+
let n_letters = 0
10+
for (let i = 0; i < s.length; i++) if (s.charAt(i) == letter) n_letters++
11+
const stack = []
12+
for (let i = 0; i < s.length; i++) {
13+
let c = s.charAt(i)
14+
while (
15+
stack.length &&
16+
stack[stack.length - 1] > c &&
17+
s.length - i + stack.length > k &&
18+
(stack[stack.length - 1] != letter || n_letters > repetition)
19+
) {
20+
if (stack.pop() == letter) repetition++
21+
}
22+
if (stack.length < k) {
23+
if (c == letter) {
24+
stack.push(c)
25+
repetition--
26+
} else if (k - stack.length > repetition) {
27+
stack.push(c)
28+
}
29+
}
30+
if (c == letter) n_letters--
31+
}
32+
33+
let sb = ''
34+
for (let c of stack) sb += c
35+
return sb
36+
}

0 commit comments

Comments
 (0)