8000 * Done with "1850. Minimum Adjacent Swaps to Reach the Kth Smallest N… · garciparedes/leetcode@b0509d1 · GitHub
[go: up one dir, main page]

Skip to content

Commit b0509d1

Browse files
committed
* Done with "1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number".
1 parent 34d44d7 commit b0509d1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from itertools import permutations
2+
3+
4+
class Solution:
5+
def getMinSwaps(self, num: str, k: int) -> int:
6+
num = list(num)
7+
8+
smallest = num.copy()
9+
for _ in range(k):
10+
self.next_smallest(smallest)
11+
12+
return self.minimum_swaps(num, smallest)
13+
14+
def next_smallest(self, num: list[str]) -> None:
15+
n = len(num)
16+
i = n - 2
17+
while i >= 0 and num[i] >= num[i + 1]:
18+
i -= 1
19+
20+
if i == -1:
21+
return
22+
23+
j = i + 1
24+
while j < n and num[i] < num[j]:
25+
j += 1
26+
27+
j -= 1
28+
29+
num[i], num[j] = num[j], num[i]
30+
31+
num[i+1:] = num[i+1:][::-1]
32+
33+
34+
35+
def minimum_swaps(self, a: list[str], b: list[str]) -> int:
36+
ans = 0
37+
for i in range(len(a)):
38+
j = i
39+
while a[j] != b[i]:
40+
j += 1
41+
42+
while i < j:
43+
a[j], a[j - 1] = a[j - 1], a[j]
44+
j -= 1
45+
ans += 1
46+
return ans
47+

0 commit comments

Comments
 (0)
0