Minimum Possible Integer After at Most K Adjacent Swaps On Digits LeetCode solution in Python

1
from sortedcontainers import SortedList
2

3

4
class Solution:
5
def minInteger(self, num: str, k: int) -> str:
6
sz, window = len(num), SortedList()
7
remainedIndices, poppedIndices = SortedList(range(sz)), []
8
while k > 0:
9
while len(window) < k + 1 and len(window) < len(remainedIndices):
10
idx = remainedIndices[len(window)]
11
window.add((num[idx], idx))
12
if not window:
13
break
14
index = window.pop(0)[1]
15
k -= remainedIndices.bisect_left(index)
16
remainedIndices.remove(index)
17
poppedIndices.append(index)
18
for idx in remainedIndices[k + 1 : len(window)]:
19
window.remove((num[idx], idx))
20
poppedSet = set(poppedIndices)
21
return "".join(num[idx] for idx in poppedIndices) + "".join(
22
num[idx] for idx in range(sz) if idx not in poppedSet
23
)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0