1class Solution:2def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:3s = list(s)4stack = []5countAll = s.count(letter)6count = 07for ind, i in enumerate(s):8while stack and stack[-1] > i:9if stack[-1] == letter and i != letter:10if countAll + count - 1 < repetition:11break12if len(stack) + len(s) - ind - 1 < k:13break14if stack[-1] == letter:15count -= 116stack.pop()17stack.append(i)18if i == letter:19count += 120countAll -= 121temp = 022while len(stack) + temp > k:23if stack[-1] == letter and count <= repetition:24temp += 125if stack[-1] == letter:26count -= 127stack.pop()28return "".join(stack) + temp * letter