1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number Medium
1/**
2 * [1850] Minimum Adjacent Swaps to Reach the Kth Smallest Number
3 *
4 * You are given a string num, representing a large integer, and an integer k.
5 * We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.
6 *
7 * For example, when num = "5489355142":
8 *
9 * The 1^st smallest wonderful integer is "5489355214".
10 * The 2^nd smallest wonderful integer is "5489355241".
11 * The 3^rd smallest wonderful integer is "5489355412".
12 * The 4^th smallest wonderful integer is "5489355421".
13 *
14 *
15 *
16 * Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the k^th smallest wonderful integer.
17 * The tests are generated in such a way that k^th smallest wonderful integer exists.
18 *
19 * Example 1:
20 *
21 * Input: num = "5489355142", k = 4
22 * Output: 2
23 * Explanation: The 4^th smallest wonderful number is "5489355421". To get this number:
24 * - Swap index 7 with index 8: "5489355<u>14</u>2" -> "5489355<u>41</u>2"
25 * - Swap index 8 with index 9: "54893554<u>12</u>" -> "54893554<u>21</u>"
26 *
27 * Example 2:
28 *
29 * Input: num = "11112", k = 4
30 * Output: 4
31 * Explanation: The 4^th smallest wonderful number is "21111". To get this number:
32 * - Swap index 3 with index 4: "111<u>12</u>" -> "111<u>21</u>"
33 * - Swap index 2 with index 3: "11<u>12</u>1" -> "11<u>21</u>1"
34 * - Swap index 1 with index 2: "1<u>12</u>11" -> "1<u>21</u>11"
35 * - Swap index 0 with index 1: "<u>12</u>111" -> "<u>21</u>111"
36 *
37 * Example 3:
38 *
39 * Input: num = "00123", k = 1
40 * Output: 1
41 * Explanation: The 1^st smallest wonderful number is "00132". To get this number:
42 * - Swap index 3 with index 4: "001<u>23</u>" -> "001<u>32</u>"
43 *
44 *
45 * Constraints:
46 *
47 * 2 <= num.length <= 1000
48 * 1 <= k <= 1000
49 * num only consists of digits.
50 *
51 */
52pub struct Solution {}
53
54// problem: https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/
55// discuss: https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/?currentPage=1&orderBy=most_votes&query=
56
57// submission codes start here
58
59impl Solution {
60 pub fn get_min_swaps(num: String, k: i32) -> i32 {
61 0
62 }
63}
64
65// submission codes end
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn test_1850() {
73 }
74}
75
Back
© 2025 bowen.ge All Rights Reserved.