Minimum Adjacent Swaps to Reach the Kth Smallest Number - Problem

You are given a string num, representing a large integer, and an integer k.

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.

For example, when num = "5489355142":

  • The 1st smallest wonderful integer is "5489355214".
  • The 2nd smallest wonderful integer is "5489355241".
  • The 3rd smallest wonderful integer is "5489355412".
  • The 4th smallest wonderful integer is "5489355421".

Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.

The tests are generated in such a way that kth smallest wonderful integer exists.

Input & Output

Example 1 — Basic Case
$ Input: num = "5489355142", k = 4
Output: 2
💡 Note: The 4th smallest wonderful number is "5489355421". We need 2 adjacent swaps to transform "5489355142" to "5489355421": swap positions 7-8 (4↔2) then swap positions 8-9 (4↔1).
Example 2 — Small Input
$ Input: num = "11112", k = 1
Output: 4
💡 Note: The 1st smallest wonderful number is "11121". We need 4 adjacent swaps to move the '2' from position 4 to position 3: swap 4 times to get "11121".
Example 3 — Multiple Steps
$ Input: num = "123", k = 2
Output: 3
💡 Note: The permutations greater than "123" are ["132", "213", "231", "312", "321"]. The 2nd smallest is "213". From "123" → "132" (1 swap) → "213" (2 more swaps) = 3 total swaps.

Constraints

  • 1 ≤ num.length ≤ 1000
  • 1 ≤ k ≤ 1000
  • num consists of digits only

Visualization

Tap to expand
Minimum Adjacent Swaps to Reach Kth Wonderful Number"123"Original Numberk=2TargetTransform"213"2nd WonderfulProcess: "123" → "132" → "213"Step 1: 1 swapStep 2: 2 swapsTotal: 3 adjacent swapsNext permutation algorithm finds lexicographically next arrangement
Understanding the Visualization
1
Input
Original number string and target k-th wonderful permutation
2
Transform
Apply next permutation algorithm k times
3
Count Swaps
Calculate total adjacent swaps needed for transformation
Key Takeaway
🎯 Key Insight: Use next permutation algorithm repeatedly instead of generating all permutations
Asked in
Google 12 Facebook 8 Amazon 6
12.0K Views
Medium Frequency
~35 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen