You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at mostk times.
Return the minimum integer you can obtain also as a string.
Example 1:
Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.
Constraints:
1 <= num.length <= 3 * 104
num consists of only digits and does not contain leading zeros.
1 <= k <= 109
Solutions
Solution 1
Thinking
We may perform at most \(k\) adjacent swaps and want the lexicographically smallest number. \(k\) can be \(10^9\) while \(n\le 3\times 10^4\), so we cannot simulate swaps one by one, nor move a digit with a linear scan at every position.
Building the answer from the left, the current place should become the smallest digit that can still reach it with the remaining budget. Moving an unused original index \(j\) to position \(i\) costs the number of not-yet-taken digits between them.
Store original indices of digits \(0\)–\(9\) in deques, and let a Fenwick tree mark which original positions have already been taken. For each candidate digit the tree evaluates the true distance in \(O(\log n)\); if it fits the remaining \(k\), we take it and update the tree. Each position inspects a constant number of digits, so the total time is \(O(n\log n)\).