Minimum Adjacent Swaps to Reach the Kth Smallest Number

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.

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

The tests are generated in such a way that the k^th smallest wonderful integer exists.

Example 1
Inputnum = "5489355142", k = 4
Output2
The 4^th smallest wonderful number is "5489355421", which can be reached from "5489355142" with two adjacent swaps.
Example 2
Inputnum = "11112", k = 4
Output4
The 4^th smallest wonderful number is "21111", which requires moving the digit 2 to the front using four adjacent swaps.

Constraints

  • 2 <= num.length <= 1000
  • 1 <= k <= 1000
  • num only consists of digits.

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate