Ctrl K

Swaps to the k-th Next Arrangement

Medium
You are given a string digits of decimal digits (it may have leading zeros) and an integer k. Consider every string obtained by rearranging the digits of digits that is strictly greater than digits as a number. Sort them in increasing order and take the k-th one (counting from one). It is guaranteed to exist. In one step you may swap two **adjacent** digits. Return the minimum number of steps that turn digits into the chosen string.
Example 1
digits='1123', k=3 → 2

Arrangements of the digits greater than 1123, in increasing order: 1132, 1213, 1231, … The third one is 1231, reached in two swaps: 1123 → 1213 → 1231.

Example 2
digits='4170', k=2 → 1

The arrangements right after 4170 are 4701 and 4710. The second one, 4710, takes a single swap of the neighbouring 1 and 7.

Example 3
digits='120', k=1 → 2

The next larger arrangement is 201, which takes two swaps: 120 → 210 → 201.

Constraints
  • 2 ≤ digits.length ≤ 1000
  • 1 ≤ k ≤ 1000
  • digits consists of digits only
  • digits has at least k rearrangements greater than itself
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPieces Without Shared Letters MediumA Note From Headline Cutouts MediumGreatest Interleave of Two Words MediumSwapping Brackets Into Balance MediumFinish the Word by Appending Medium
loading Python…
Input
digits='1123', k=3
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 76 tests on the server, hidden ones included.