Minimum Adjacent Swaps to Reach the Kth Smallest Number - Problem
Finding the Kth Smallest Wonderful Number

Imagine you have a string of digits representing a large number, and you want to find the kth smallest "wonderful" number that can be formed by rearranging these digits.

A wonderful number is defined as any permutation of the original digits that is greater than the original number. Your task is to find the minimum number of adjacent swaps needed to transform the original number into the kth smallest wonderful number.

Example:
Given num = "5489355142" and k = 4:
• 1st wonderful: "5489355214"
• 2nd wonderful: "5489355241"
• 3rd wonderful: "5489355412"
• 4th wonderful: "5489355421"

You need to return the minimum adjacent swaps to reach the 4th wonderful number.

Key Insight: This combines the classic "next permutation" algorithm with counting adjacent swaps - a beautiful blend of combinatorics and greedy algorithms!

Input & Output

example_1.py — Basic Case
$ Input: num = "5489355142", k = 4
Output: 12
💡 Note: The 4th smallest wonderful number is "5489355421". We need to find the minimum adjacent swaps to transform "5489355142" to "5489355421", which requires 12 swaps.
example_2.py — Small Input
$ Input: num = "11112", k = 1
Output: 4
💡 Note: The 1st wonderful number is "11121". We need 4 adjacent swaps to move the last '2' to the second-to-last position.
example_3.py — Edge Case
$ Input: num = "00123", k = 1
Output: 1
💡 Note: The 1st wonderful number is "00132". Only 1 adjacent swap is needed to exchange the last two digits.

Constraints

  • 1 ≤ num.length ≤ 1000
  • num consists of only digits
  • 1 ≤ k ≤ 1000
  • kth smallest wonderful integer is guaranteed to exist

Visualization

Tap to expand
The Library Book Arrangement AnalogyCurrent Arrangement: 1 3 2 4Book1Book3Book2Book4Pivot: 3 > 2Next Arrangement: 1 4 2 3 (2 swaps needed)Book1Book4Book2Book32 Adjacent SwapsAlgorithm Steps:1. Find pivot: rightmost decreasing point2. Find successor: next larger element3. Bubble successor to pivot position4. Reverse the suffix for minimum
Understanding the Visualization
1
Find the Pivot
Locate the rightmost position where arrangement can increase
2
Find the Successor
Find the smallest element larger than pivot from the right
3
Bubble & Count
Move successor to pivot position while counting swaps
4
Reverse Suffix
Optimize the remaining part to get the immediate next permutation
Key Takeaway
🎯 Key Insight: The next permutation algorithm combined with swap counting gives us the exact answer without generating all permutations, making it efficient for large inputs.
Asked in
Google 45 Amazon 38 Meta 29 Microsoft 22
43.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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